Skip to content

auth: RequireBearerToken returns 403 instead of 401 for an expired token missing a scope #1349

Closed

Description

@ilaigold

Describe the bug

While reading through RequireBearerToken I noticed that verify checks RequireBearerTokenOptions.Scopes before expiry. So a token that's expired and also missing a required scope gets 403 insufficient scope instead of 401 token expired. Same for a token with no expiration when AllowMissingExpiration is false.

Per RFC 6750 §3.1 an expired token is invalid_token (401). It doesn't grant anything, so "insufficient scope" doesn't really apply, and the two codes ask the client for different things: 401 means get a new token, 403 means ask for more scopes. The SDK's own client doesn't re-authorize on a 403 without error="insufficient_scope" (see AuthorizationCodeHandler.Authorize), so the call just fails.

To Reproduce

  1. Run this against main (6737e73):
package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/modelcontextprotocol/go-sdk/auth"
)

func main() {
	// Token passes verification but expired an hour ago and has no scopes.
	verifier := func(context.Context, string, *http.Request) (*auth.TokenInfo, error) {
		return &auth.TokenInfo{Expiration: time.Now().Add(-time.Hour)}, nil
	}
	h := auth.RequireBearerToken(verifier, &auth.RequireBearerTokenOptions{
		ResourceMetadataURL: "https://example.com/.well-known/oauth-protected-resource",
		Scopes:              []string{"read"},
	})(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))

	req := httptest.NewRequest("GET", "/mcp", nil)
	req.Header.Set("Authorization", "Bearer expired-token")
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	fmt.Println(rec.Code, rec.Body.String())
	fmt.Println("WWW-Authenticate:", rec.Header().Get("WWW-Authenticate"))
}
  1. It prints:
403 insufficient scope

WWW-Authenticate: Bearer resource_metadata="https://example.com/.well-known/oauth-protected-resource", scope="read"

Expected behavior

401 token expired. The scope check should only run on a token that's otherwise valid.

Logs

N/A, the repro output above is all there is.

Additional context

AI assistance: I used Claude Code to help dig into this and write the repro and this report.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions