Skip to content

mcp-server: return 401 when API key is missing - #90

Open
arnabnandy7 wants to merge 1 commit into
spring-ai-community:mainfrom
arnabnandy7:fix/mcp-api-key-401
Open

mcp-server: return 401 when API key is missing#90
arnabnandy7 wants to merge 1 commit into
spring-ai-community:mainfrom
arnabnandy7:fix/mcp-api-key-401

Conversation

@arnabnandy7

Copy link
Copy Markdown

Closes #46.

Problem

When an API-key-protected MCP endpoint receives a request without an API key, the API key authentication filter passes the request through so another configured authentication mechanism can authenticate it.

If no mechanism authenticates the request, Spring Security currently uses its default entry point and returns 403 Forbidden. Since the request is unauthenticated, it should instead return 401 Unauthorized.

An unconditional API key entry point is not sufficient because it overrides the OAuth2 resource server entry point when API key and OAuth2 authentication are configured together. This prevents the OAuth2 WWW-Authenticate challenge from being returned.

Changes

  • Configure a 401 Unauthorized entry point for API-key authentication when MCP OAuth2 security is not configured.
  • Preserve the OAuth2 entry point when API key and OAuth2 authentication are used together.
  • Update the missing API key test to expect 401 Unauthorized.
  • Add regression coverage verifying that combined API key and OAuth2 configuration still returns a WWW-Authenticate header.
  • Document the response behavior for missing and invalid API keys.

Result

  • API-key-only server with no credentials: 401 Unauthorized
  • API key + OAuth2 server with no credentials: 401 Unauthorized with the OAuth2 WWW-Authenticate challenge
  • Invalid API key: 401 Unauthorized
  • Successful alternative authentication: request proceeds normally
  • Authenticated requests without sufficient authorization: existing 403 Forbidden behavior is unchanged

Testing

./mvnw -pl mcp-server-security \
  -Dtest=McpApiKeyConfigurerTest,ApiKeyAuthenticationFilterTests \
  clean test

Signed-off-by: Arnab Nandy <arnab_nandy7@yahoo.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MCP Server: API key server should return 401 when missing API key

1 participant