Web api将名称和密码设置为request.BasicAuth
登录验证的路由-app.HandleGET、/v1/users/token、u.token 我们可以从request.BasicAuth获取名称和密码Web api将名称和密码设置为request.BasicAuth,api,authentication,go,Api,Authentication,Go,登录验证的路由-app.HandleGET、/v1/users/token、u.token 我们可以从request.BasicAuth获取名称和密码 func (u *User) Token(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error { ... name, pass, ok := r.BasicAuth() ... } 但是如
func (u *User) Token(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {
...
name, pass, ok := r.BasicAuth()
...
}
但是如何从客户端web url设置名称和密码?在浏览器要求用户提供基本身份验证凭据之前,必须使用状态代码401 Unauthorized拒绝请求访问。您应该将标题WWW Authenticate设置为Basic realm=您的消息。 另见 因此,在代码中,当ok为false时,应拒绝该请求:
func (u *User) Token(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {
...
name, pass, ok := r.BasicAuth()
if !ok {
w.Header().Set("WWW-Authenticate", "Basic realm=\"Your message\"")
http.Error(w, "Must supply authentication credentials", http.StatusUnauthorized)
return
}
}
这是否意味着我应该设置名称并传入客户端头,然后发送/v1/users/token url?正确。该示例检查客户端是否发送了凭据,在这种情况下,ok为true。如果没有,请求将被拒绝