ccd
ccd

Reputation: 6948

Web api set name and password to request.BasicAuth

The route for login authenticate -- app.Handle("GET", "/v1/users/token", u.Token).

We can get name and password from 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()
    ...
}

But how can I set name and pass from client web url?

Upvotes: 0

Views: 50

Answers (1)

xarantolus
xarantolus

Reputation: 2029

Before a browser asks the user to supply basic auth credentials, you have to deny the request access (using status code 401 Unauthorized). You should set the header WWW-Authenticate to Basic realm="Your message". Also see this article.

So in your code, when ok is false, you should deny that request:

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
    }
}

Upvotes: 1

Related Questions