RequireBearerToken returns a piece of middleware that verifies a bearer token using the verifier. If verification succeeds, the [TokenInfo] is added to the request's context and the request proceeds. If verification fails, the request fails with a 401 Unauthenticated, and the WWW-Authenticate header
(verifier TokenVerifier, opts *RequireBearerTokenOptions)
| 67 | // |
| 68 | // [protected resource metadata]: https://datatracker.ietf.org/doc/rfc9728 |
| 69 | func RequireBearerToken(verifier TokenVerifier, opts *RequireBearerTokenOptions) func(http.Handler) http.Handler { |
| 70 | // Based on typescript-sdk/src/server/auth/middleware/bearerAuth.ts. |
| 71 | |
| 72 | return func(handler http.Handler) http.Handler { |
| 73 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 74 | tokenInfo, errmsg, code := verify(r, verifier, opts) |
| 75 | if code != 0 { |
| 76 | if code == http.StatusUnauthorized || code == http.StatusForbidden { |
| 77 | if opts != nil { |
| 78 | var params []string |
| 79 | if opts.ResourceMetadataURL != "" { |
| 80 | params = append(params, fmt.Sprintf("resource_metadata=%q", opts.ResourceMetadataURL)) |
| 81 | } |
| 82 | if len(opts.Scopes) > 0 { |
| 83 | params = append(params, fmt.Sprintf("scope=%q", strings.Join(opts.Scopes, " "))) |
| 84 | } |
| 85 | if len(params) > 0 { |
| 86 | w.Header().Add("WWW-Authenticate", "Bearer "+strings.Join(params, ", ")) |
| 87 | } |
| 88 | } |
| 89 | } |
| 90 | http.Error(w, errmsg, code) |
| 91 | return |
| 92 | } |
| 93 | r = r.WithContext(context.WithValue(r.Context(), tokenInfoKey{}, tokenInfo)) |
| 94 | handler.ServeHTTP(w, r) |
| 95 | }) |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | func verify(req *http.Request, verifier TokenVerifier, opts *RequireBearerTokenOptions) (_ *TokenInfo, errmsg string, code int) { |
| 100 | // Extract bearer token. |
searching dependent graphs…