From 6e25028eaee1b76a2d3a0ed67ce64e335cd1d7f0 Mon Sep 17 00:00:00 2001 From: kanywst Date: Mon, 12 Oct 2026 22:33:19 +0900 Subject: [PATCH] examples: check token audience and set UserID in auth examples --- examples/auth/server/main.go | 22 +++++++++++++++++++++- examples/server/auth-middleware/main.go | 2 ++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/examples/auth/server/main.go b/examples/auth/server/main.go index 94ad9ae3f..50a63100d 100644 --- a/examples/auth/server/main.go +++ b/examples/auth/server/main.go @@ -67,6 +67,7 @@ func verifyToken(ctx context.Context, token string, _ *http.Request) (*auth.Toke Scope string `json:"scope"` Exp int64 `json:"exp"` Sub string `json:"sub"` + Aud any `json:"aud"` } if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { return nil, err @@ -76,6 +77,21 @@ func verifyToken(ctx context.Context, token string, _ *http.Request) (*auth.Toke return nil, auth.ErrInvalidToken } + var aud []string + switch v := result.Aud.(type) { + case string: + aud = []string{v} + case []any: + for _, a := range v { + if s, ok := a.(string); ok { + aud = append(aud, s) + } + } + } + if !oauthex.MatchesResource(aud, resourceURL()) { + return nil, auth.ErrInvalidToken + } + return &auth.TokenInfo{ Scopes: strings.Fields(result.Scope), Expiration: time.Unix(result.Exp, 0), @@ -95,10 +111,14 @@ func echo(ctx context.Context, req *mcp.CallToolRequest, args args) (*mcp.CallTo }, nil, nil } +func resourceURL() string { + return fmt.Sprintf("http://localhost:%d/mcp", *port) +} + func main() { flag.Parse() metadata := &oauthex.ProtectedResourceMetadata{ - Resource: fmt.Sprintf("http://localhost:%d/mcp", *port), + Resource: resourceURL(), AuthorizationServers: []string{authorizationServer}, ScopesSupported: []string{"read"}, } diff --git a/examples/server/auth-middleware/main.go b/examples/server/auth-middleware/main.go index f9ac34f77..e6665e41f 100644 --- a/examples/server/auth-middleware/main.go +++ b/examples/server/auth-middleware/main.go @@ -105,6 +105,7 @@ func verifyJWT(ctx context.Context, tokenString string, _ *http.Request) (*auth. return &auth.TokenInfo{ Scopes: claims.Scopes, // User permissions Expiration: claims.ExpiresAt.Time, // Token expiration time + UserID: claims.UserID, // Binds the session to this user }, nil } @@ -125,6 +126,7 @@ func verifyAPIKey(ctx context.Context, apiKey string, _ *http.Request) (*auth.To return &auth.TokenInfo{ Scopes: key.Scopes, // User permissions Expiration: time.Now().Add(24 * time.Hour), // 24 hour expiration + UserID: key.UserID, // Binds the session to this user }, nil }