MCPcopy Create free account
hub / github.com/modelcontextprotocol/go-sdk / RequireBearerToken

Function RequireBearerToken

auth/auth.go:69–97  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

67//
68// [protected resource metadata]: https://datatracker.ietf.org/doc/rfc9728
69func 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
99func verify(req *http.Request, verifier TokenVerifier, opts *RequireBearerTokenOptions) (_ *TokenInfo, errmsg string, code int) {
100 // Extract bearer token.

Callers 8

TestTokenInfoFunction · 0.92
mainFunction · 0.92
mainFunction · 0.92
TestRequireBearerTokenFunction · 0.85

Calls 3

verifyFunction · 0.85
ErrorMethod · 0.45
ServeHTTPMethod · 0.45

Used in the wild real call sites across dependent graphs

searching dependent graphs…