MCP 安全
Spring AI MCP Security 模块为 Spring AI 中的模型上下文协议(MCP)实现提供了全面的 OAuth 2.0 和基于 API 密钥的安全支持。这个社区驱动的项目使开发者能够使用行业标准的身份验证和授权机制来保护 MCP 服务器和客户端。
概览
MCP Security 模块提供三个主要组件:
- MCP 服务器安全 — 为 Spring AI MCP 服务器提供 OAuth 2.0 资源服务器功能和 API 密钥认证
- MCP 客户端安全 — 为 Spring AI MCP 客户端提供 OAuth 2.0 客户端支持
- MCP 授权服务器 — 基于 Spring Authorization Server 的增强版,包含 MCP 特定功能
该项目使开发者能够:
- 使用 OAuth 2.0 认证和基于 API 密钥的访问控制来保护 MCP 服务器
- 为 MCP 客户端配置 OAuth 2.0 授权流程
- 专门为 MCP 工作流搭建授权服务器
- 对 MCP 工具和资源实现精细化访问控制
MCP 服务器安全
MCP 服务器安全模块为 Spring AI 的 MCP 服务器 提供 OAuth 2.0 资源服务器功能,同时还提供基于 API 密钥认证的基础支持。
依赖项
将以下依赖添加到您的项目中:
<dependencies>
<dependency>
<groupId>org.springaicommunity</groupId>
<artifactId>mcp-server-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- OPTIONAL: For OAuth2 support -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
</dependencies>
implementation 'org.springaicommunity:mcp-server-security'
implementation 'org.springframework.boot:spring-boot-starter-security'
// OPTIONAL: For OAuth2 support
implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
OAuth 2.0 配置
基础 OAuth 2.0 设置
首先,在 application.properties 中启用 MCP 服务器:
spring.ai.mcp.server.name=my-cool-mcp-server
# 支持的协议:STREAMABLE, STATELESS
spring.ai.mcp.server.protocol=STREAMABLE
然后,使用 Spring Security 的标准 API 配合提供的 MCP 配置器进行安全配置:
@Configuration
@EnableWebSecurity
class McpServerConfiguration {
@Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
private String issuerUrl;
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
// 强制每个请求使用令牌进行身份验证
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
// 在 MCP 服务器上配置 OAuth2
.with(
McpServerOAuth2Configurer.mcpServerOAuth2(),
(mcpAuthorization) -> {
// 必填:issuerURI
mcpAuthorization.authorizationServer(issuerUrl);
// 可选:验证 JWT token 中的 `aud` 声明
mcpAuthorization.validateAudienceClaim(true);
}
)
.build();
}
}
仅保护工具调用
你可以只保护工具调用,而将其他 MCP 操作(如 initialize 和 tools/list)保持公开:
@Configuration
@EnableWebSecurity
@EnableMethodSecurity // 启用基于注解的方法安全
class McpServerConfiguration {
@Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
private String issuerUrl;
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
// 开放服务器上的所有请求
.authorizeHttpRequests(auth -> {
auth.requestMatcher("/mcp").permitAll();
auth.anyRequest().authenticated();
})
// 在 MCP 服务器上配置 OAuth2
.with(
McpResourceServerConfigurer.mcpServerOAuth2(),
(mcpAuthorization) -> {
// 必填:issuerURI
mcpAuthorization.authorizationServer(issuerUrl);
}
)
.build();
}
}
使用 @PreAuthorize 注解对工具调用进行 安全控制:
@Service
public class MyToolsService {
@PreAuthorize("isAuthenticated()")
@McpTool(name = "greeter", description = "一个根据选择语言打招呼的工具")
public String greet(
@ToolParam(description = "打招呼的语言(示例:english, french, ...)") String language
) {
if (!StringUtils.hasText(language)) {
language = "";
}
return switch (language.toLowerCase()) {
case "english" -> "Hello you!";
case "french" -> "Salut toi!";
default -> "我不理解语言 \"%s\",所以我只能说 Hello!".formatted(language);
};
}
}
你也可以在工具方法中直接访问当前身份验证信息:
@McpTool(name = "greeter", description = "一个根据选择语言向用户打招呼的工具")
@PreAuthorize("isAuthenticated()")
public String greet(
@ToolParam(description = "打招呼的语言(示例:english, french, ...)") String language
) {
if (!StringUtils.hasText(language)) {
language = "";
}
var authentication = SecurityContextHolder.getContext().getAuthentication();
var name = authentication.getName();
return switch (language.toLowerCase()) {
case "english" -> "Hello, %s!".formatted(name);
case "french" -> "Salut %s!".formatted(name);
default -> ("我不理解语言 \"%s\",所以我只能说 Hello %s!").formatted(language, name);
};
}
API 密钥认证
MCP 服务器安全模块还支持基于 API Key 的身份验证。你需要提供自己的 ApiKeyEntityRepository 实现,用于存储 ApiKeyEntity 对象。
提供了一个示例实现 InMemoryApiKeyEntityRepository,以及默认的 ApiKeyEntityImpl:
InMemoryApiKeyEntityRepository 使用 bcrypt 存储 API Key,这在计算上开销较大,不适合高流量生产环境。生产环境中,请自行实现 ApiKeyEntityRepository。示例配置:
@Configuration
@EnableWebSecurity
class McpServerConfiguration {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests(authz -> authz.anyRequest().authenticated())
.with(
mcpServerApiKey(),
(apiKey) -> {
// 必填:API Key 仓库
apiKey.apiKeyRepository(apiKeyRepository());
// 可选:指定包含 API Key 的请求头名称
// 例如这里 API Key 将通过 "CUSTOM-API-KEY: <value>" 发送
// apiKey.headerName("CUSTOM-API-KEY");
// 可选:自定义请求转换器,将 HTTP 请求转换为认证对象
// 适用于 "Authorization: Bearer <value>" 的情况
// apiKey.authenticationConverter(request -> {
// var key = extractKey(request);
// return ApiKeyAuthenticationToken.unauthenticated(key);
// });
}
)
.build();
}
/**
* 提供 {@link ApiKeyEntity} 的仓库实现
*/
private ApiKeyEntityRepository<ApiKeyEntityImpl> apiKeyRepository() {
var apiKey = ApiKeyEntityImpl.builder()
.name("test api key")
.id("api01")
.secret("mycustomapikey")
.build();
return new InMemoryApiKeyEntityRepository<>(List.of(apiKey));
}
}
使用此配置后,你可以通过请求头 X-API-key: api01.mycustomapikey 调用你的 MCP 服务器。
已知限制
- 已弃用的 SSE 传输不再支持,请使用 Streamable HTTP 或 Stateless 传输。
- 基于 WebFlux 的服务器不受支持。
- 不透明令牌(Opaque Token)不支持,请使用 JWT。
MCP 客户端安全
MCP Client Security 模块为 Spring AI 的 MCP 客户端 提供 OAuth 2.0 支持,既适用于基于 HttpClient 的客户端(来自 spring-ai-starter-mcp-client),也适用于基于 WebClient 的客户端(来自 spring-ai-starter-mcp-client-webflux)。
McpSyncClient。依赖项
<dependency>
<groupId>org.springaicommunity</groupId>
<artifactId>mcp-client-security</artifactId>
</dependency>
implementation 'org.springaicommunity:mcp-client-security'
授权流程
共有三种 OAuth 2.0 授权流程可用于获取令牌:
- 授权码模式(Authorization Code Flow) —— 适用于需要用户级权限,并且所有 MCP 请求都在用户请求上下文中执行的场景。
- 客户端凭证模式(Client Credentials Flow) —— 用于纯机器间通信(machine-to-machine),无需用户参与。
- 混合模式(Hybrid Flow) —— 用于部分操作(如
initialize或tools/list)在无用户的情况下执行,但工具调用需要用户级权限的场景;该模式结合前两种流程。
- 当你需要 用户级权限,并且所有 MCP 请求都在 用户上下文 中执行时,请使用 授权码模式(Authorization Code Flow)。
- 当你的场景是 机器与机器之间的通信(无需用户参与)时,请使用 客户端凭证模式(Client Credentials Flow)。
- 当你通过 Spring Boot 配置 MCP 客户端时,请使用 混合模式(Hybrid Flow),因为工具发现(tool discovery)是在应用启动时执行的,而此时并没有用户存在。
常见设置
对于所有 OAuth 2.0 流程,都需要在 application.properties 中启用 Spring Security 的 OAuth2 客户端支持:
# 确保 MCP 客户端为同步模式
spring.ai.mcp.client.type=SYNC
# 用于 authorization_code 或 hybrid 流程
spring.security.oauth2.client.registration.authserver.client-id=<THE CLIENT ID>
spring.security.oauth2.client.registration.authserver.client-secret=<THE CLIENT SECRET>
spring.security.oauth2.client.registration.authserver.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.authserver.provider=authserver
# 用于 client_credentials 或 hybrid 流程
spring.security.oauth2.client.registration.authserver-client-credentials.client-id=<THE CLIENT ID>
spring.security.oauth2.client.registration.authserver-client-credentials.client-secret=<THE CLIENT SECRET>
spring.security.oauth2.client.registration.authserver-client-credentials.authorization-grant-type=client_credentials
spring.security.oauth2.client.registration.authserver-client-credentials.provider=authserver
# 授权服务器配置
spring.security.oauth2.client.provider.authserver.issuer-uri=<THE ISSUER URI OF YOUR AUTH SERVER>
接着,创建一个配置类以启用 OAuth2 客户端功能:
@Configuration
@EnableWebSecurity
class SecurityConfiguration {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
// 在此示例中,客户端应用的所有端点均不启用安全性
.authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
// 启用 OAuth2 客户端功能
.oauth2Client(Customizer.withDefaults())
.build();
}
}
基于 HttpClient 的客户端
当使用 spring-ai-starter-mcp-client 时,需要配置一个 McpSyncHttpClientRequestCustomizer Bean:
@Configuration
class McpConfiguration {
@Bean
McpSyncClientCustomizer syncClientCustomizer() {
return (name, syncSpec) ->
syncSpec.transportContextProvider(
new AuthenticationMcpTransportContextProvider()
);
}
@Bean
McpSyncHttpClientRequestCustomizer requestCustomizer(
OAuth2AuthorizedClientManager clientManager
) {
// clientRegistration 的名称 “authserver”
// 必须与 application.properties 中的配置名称保持一致
return new OAuth2AuthorizationCodeSyncHttpRequestCustomizer(
clientManager,
"authserver"
);
}
}
可用的自定义器包括:
- OAuth2AuthorizationCodeSyncHttpRequestCustomizer —— 用于 authorization code 授权码流程
- OAuth2ClientCredentialsSyncHttpRequestCustomizer —— 用于 client credentials 客户端凭证流程
- OAuth2HybridSyncHttpRequestCustomizer —— 用于 hybrid 混合流程
基于 WebClient 的客户端
当使用 spring-ai-starter-mcp-client-webflux 时,需要通过配置带有 MCP ExchangeFilterFunction 的 WebClient.Builder 来启用 OAuth 2.0 认证:
@Configuration
class McpConfiguration {
@Bean
McpSyncClientCustomizer syncClientCustomizer() {
return (name, syncSpec) ->
syncSpec.transportContextProvider(
new AuthenticationMcpTransportContextProvider()
);
}
@Bean
WebClient.Builder mcpWebClientBuilder(OAuth2AuthorizedClientManager clientManager) {
// clientRegistration 名称 "authserver"
// 必须与 application.properties 中保持一致
return WebClient.builder().filter(
new McpOAuth2AuthorizationCodeExchangeFilterFunction(
clientManager,
"authserver"
)
);
}
}
可用的 FilterFunction:
McpOAuth2AuthorizationCodeExchangeFilterFunction—— 用于 authorization code 授权码流程McpOAuth2ClientCredentialsExchangeFilterFunction—— 用于 client credentials 客户端凭证流程McpOAuth2HybridExchangeFilterFunction—— 用于 hybrid 混合流程
绕过 Spring AI 自动配置的方法
Spring AI 的自动配置会在应用启动时初始化 MCP 客户端,而这在使用 “基于用户” 的身份验证场景中可能会产生问题。为避免此类问题,可使用以下两种方法之一:
方案一:禁用 @Tool 自动配置
通过声明一个空的 ToolCallbackResolver Bean 来禁用 Spring AI 的 @Tool 自动配置:
@Configuration
public class McpConfiguration {
@Bean
ToolCallbackResolver resolver() {
return new StaticToolCallbackResolver(List.of());
}
}
方案二:以编程方式配置 MCP 客户端
无需使用 Spring Boot 属性,而是手动配置 MCP 客户端。
1. 基于 HttpClient 的客户端:
@Bean
McpSyncClient client(
ObjectMapper objectMapper,
McpSyncHttpClientRequestCustomizer requestCustomizer,
McpClientCommonProperties commonProps
) {
var transport = HttpClientStreamableHttpTransport.builder(mcpServerUrl)
.clientBuilder(HttpClient.newBuilder())
.jsonMapper(new JacksonMcpJsonMapper(objectMapper))
.httpRequestCustomizer(requestCustomizer)
.build();
var clientInfo = new McpSchema.Implementation("client-name", commonProps.getVersion());
return McpClient.sync(transport)
.clientInfo(clientInfo)
.requestTimeout(commonProps.getRequestTimeout())
.transportContextProvider(new AuthenticationMcpTransportContextProvider())
.build();
}
2. 基于 WebClient 的客户端:
@Bean
McpSyncClient client(
WebClient.Builder mcpWebClientBuilder,
ObjectMapper objectMapper,
McpClientCommonProperties commonProperties
) {
var builder = mcpWebClientBuilder.baseUrl(mcpServerUrl);
var transport = WebClientStreamableHttpTransport.builder(builder)
.jsonMapper(new JacksonMcpJsonMapper(objectMapper))
.build();
var clientInfo = new McpSchema.Implementation("clientName", commonProperties.getVersion());
return McpClient.sync(transport)
.clientInfo(clientInfo)
.requestTimeout(commonProperties.getRequestTimeout())
.transportContextProvider(new AuthenticationMcpTransportContextProvider())
.build();
}
将 MCP 客户端加入 Chat Client:
var chatResponse = chatClient.prompt("Prompt the LLM to do the thing")
.toolCallbacks(new SyncMcpToolCallbackProvider(mcpClient1, mcpClient2, mcpClient3))
.call()
.content();
已知限制
- 不支持 Spring WebFlux 服务器。
- Spring AI 的自动配置会在应用启动时初始化 MCP 客户端,这在基于用户的身份验证场景中需要额外的解决方案。
- 与服务器模块不同,客户端实现支持 SSE 传输方式,且可同时用于
HttpClient和WebClient。
MCP 授权服务器
MCP 授权服务器模块对 Spring Security 的 OAuth 2.0 授权服务器 进行了增强,增加了与 MCP 授权规范 相关的功能,例如 动态客户端注册(Dynamic Client Registration) 和 资源指示器(Resource Indicators)。
依赖项
<dependency>
<groupId>org.springaicommunity</groupId>
<artifactId>mcp-authorization-server</artifactId>
</dependency>
implementation 'org.springaicommunity:mcp-authorization-server'
配置
将授权服务器配置到你的 application.yml 中:
spring:
application:
name: sample-authorization-server
security:
oauth2:
authorizationserver:
client:
default-client:
token:
access-token-time-to-live: 1h
registration:
client-id: "default-client"
client-secret: "{noop}default-secret"
client-authentication-methods:
- "client_secret_basic"
- "none"
authorization-grant-types:
- "authorization_code"
- "client_credentials"
redirect-uris:
- "http://127.0.0.1:8080/authorize/oauth2/code/authserver"
- "http://localhost:8080/authorize/oauth2/code/authserver"
# mcp-inspector
- "http://localhost:6274/oauth/callback"
# claude code
- "https://claude.ai/api/mcp/auth_callback"
user:
# A single user, named "user"
name: user
password: password
server:
servlet:
session:
cookie:
# Override the default cookie name (JSESSIONID).
# This allows running multiple Spring apps on localhost, and they'll each have their own cookie.
# Otherwise, since the cookies do not take the port into account, they are confused.
name: MCP_AUTHORIZATION_SERVER_SESSIONID
然后通过配置 Security Filter Chain 激活授权服务器功能:
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
// all requests must be authenticated
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
// enable authorization server customizations
.with(McpAuthorizationServerConfigurer.mcpAuthorizationServer(), withDefaults())
// enable form-based login, for user "user"/"password"
.formLogin(withDefaults())
.build();
}
已知限制
- 不支持 Spring WebFlux 服务器。
- 每个客户端都支持所有资源标识符。
示例与集成
samples 目录 包含本项目所有模块的可运行示例,包括集成测试。
通过 mcp-server-security 及配套的 mcp-authorization-server,你可以与以下工具集成:
- Cursor
- Claude Desktop
- MCP Inspector