MCP安全
| 这仍在进行中。文档和API可能会在未来版本中有所变化。 |
Spring AI MCP 安全模块为 Spring AI 中的模型上下文协议实现提供了全面的基于 OAuth 2.0 和基于 API 密钥的安全支持。这一由社区驱动的项目使开发者能够通过行业标准的认证和授权机制保护MCP服务器和客户端的安全。
| 该模块是 spring-ai-community/mcp-security 项目的一部分,目前仅支持 Spring AI 的 1.1.x 分支。 这是一个社区驱动的项目,尚未获得 Spring AI 或 MCP 项目的官方认可。 |
概述
MCP安全模块提供三个主要组件:
-
MCP 服务器安全 - OAuth 2.0 资源服务器及 Spring AI MCP 服务器的 API 密钥认证
-
MCP 客户端安全 - OAuth 2.0 客户端支持 Spring AI MCP 客户端
-
MCP 授权服务器——具有 MCP 特定功能的增强型 Spring 授权服务器
该项目使开发者能够:
-
具备OAuth 2.0认证和基于API密钥访问的安全MCP服务器
-
配置带有OAuth 2.0授权流的MCP客户端
-
建立专门为MCP工作流程设计的授权服务器
-
为MCP工具和资源实现细粒度访问控制
MCP服务器安全
MCP 服务器安全模块为 Spring AI 的 MCP 服务器提供 OAuth 2.0 资源服务器功能。 它还提供了基于API密钥的认证基础支持。
| 该模块仅兼容基于 Spring WebMVC 的服务器。 |
依赖
为你的项目添加以下依赖:
-
Maven
-
Gradle
<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:
spring.ai.mcp.server.name=my-cool-mcp-server
# Supported protocols: 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
// Enforce authentication with token on EVERY request
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
// Configure OAuth2 on the MCP server
.with(
McpServerOAuth2Configurer.mcpServerOAuth2(),
(mcpAuthorization) -> {
// REQUIRED: the issuerURI
mcpAuthorization.authorizationServer(issuerUrl);
// OPTIONAL: enforce the `aud` claim in the JWT token.
// Not all authorization servers support resource indicators,
// so it may be absent. Defaults to `false`.
// See RFC 8707 Resource Indicators for OAuth 2.0
// https://www.rfc-editor.org/rfc/rfc8707.html
mcpAuthorization.validateAudienceClaim(true);
}
)
.build();
}
}
仅保护工具调用
你可以配置服务器只保护工具调用,保留其他MCP作(比如初始化和工具/列表) 公共:
@Configuration
@EnableWebSecurity
@EnableMethodSecurity // Enable annotation-driven security
class McpServerConfiguration {
@Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
private String issuerUrl;
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
// Open every request on the server
.authorizeHttpRequests(auth -> {
auth.requestMatcher("/mcp").permitAll();
auth.anyRequest().authenticated();
})
// Configure OAuth2 on the MCP server
.with(
McpResourceServerConfigurer.mcpServerOAuth2(),
(mcpAuthorization) -> {
// REQUIRED: the issuerURI
mcpAuthorization.authorizationServer(issuerUrl);
}
)
.build();
}
}
然后,利用@PreAuthorize带方法安全的注释:
@Service
public class MyToolsService {
@PreAuthorize("isAuthenticated()")
@McpTool(name = "greeter", description = "A tool that greets you, in the selected language")
public String greet(
@ToolParam(description = "The language for the greeting (example: english, french, ...)") String language
) {
if (!StringUtils.hasText(language)) {
language = "";
}
return switch (language.toLowerCase()) {
case "english" -> "Hello you!";
case "french" -> "Salut toi!";
default -> "I don't understand language \"%s\". So I'm just going to say Hello!".formatted(language);
};
}
}
你也可以直接从工具方法访问当前认证,使用以下方式安全上下文持有者:
@McpTool(name = "greeter", description = "A tool that greets the user by name, in the selected language")
@PreAuthorize("isAuthenticated()")
public String greet(
@ToolParam(description = "The language for the greeting (example: 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 -> ("I don't understand language \"%s\". " +
"So I'm just going to say Hello %s!").formatted(language, name);
};
}
API密钥认证
MCP 服务器安全模块还支持基于 API 密钥的认证。你需要提供你自己的实现ApiKeyEntityRepository用于存储ApiKeyEntity对象。
示例实现为InMemoryApiKeyEntityRepository同时附带默认值ApiKeyEntityImpl:
这InMemoryApiKeyEntityRepository使用 bcrypt 存储 API 密钥,计算量较大。它不适合高流量的生产用途。生产方面,自己实现ApiKeyEntityRepository. |
@Configuration
@EnableWebSecurity
class McpServerConfiguration {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests(authz -> authz.anyRequest().authenticated())
.with(
mcpServerApiKey(),
(apiKey) -> {
// REQUIRED: the repo for API keys
apiKey.apiKeyRepository(apiKeyRepository());
// OPTIONAL: name of the header containing the API key.
// Here for example, api keys will be sent with "CUSTOM-API-KEY: <value>"
// Replaces .authenticationConverter(...) (see below)
//
// apiKey.headerName("CUSTOM-API-KEY");
// OPTIONAL: custom converter for transforming an http request
// into an authentication object. Useful when the header is
// "Authorization: Bearer <value>".
// Replaces .headerName(...) (see above)
//
// apiKey.authenticationConverter(request -> {
// var key = extractKey(request);
// return ApiKeyAuthenticationToken.unauthenticated(key);
// });
}
)
.build();
}
/**
* Provide a repository of {@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));
}
}
通过这种配置,你可以用一个头部调用你的MCP服务器X-API-key: api01.mycustomapikey.
MCP 客户端安全
MCP 客户端安全模块为 Spring AI 的 MCP 客户端提供 OAuth 2.0 支持 ,支持两个基于 HttpClient 的客户端(来自Spring-AI-starter-mcp-client)以及基于WebClient的客户端(来自)Spring-AI-starter-mcp-client-webflux).
该模块支持McpSync客户端只。 |
依赖
-
Maven
-
Gradle
<dependency>
<groupId>org.springaicommunity</groupId>
<artifactId>mcp-client-security</artifactId>
</dependency>
implementation 'org.springaicommunity:mcp-client-security'
授权流程
有三种OAuth 2.0流程可用于获取Tokens:
-
授权代码流程——当每个MCP请求都在用户请求的上下文中发出时,用于用户级权限
-
客户端凭证流程——适用于机器对机器的场景,且无人工参与
-
混合流程——结合两种流程,适用于某些作(如
初始化或工具/列表)发生时没有用户,但工具调用需要用户级权限
| 当你拥有用户级权限且所有MCP请求都发生在用户上下文中时,使用授权代码流程。使用客户端凭证进行机器间通信。使用 Spring Boot 属性进行 MCP 客户端配置时,请使用混合流程,因为工具发现是在启动时进行的,无需用户参与。 |
常见配置
对于所有流程,请在你的application.properties:
# Ensure MCP clients are sync
spring.ai.mcp.client.type=SYNC
# For authorization_code or hybrid flow
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
# For client_credentials or hybrid flow
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
# Authorization server configuration
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
// in this example, the client app has no security on its endpoints
.authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
// turn on OAuth2 support
.oauth2Client(Customizer.withDefaults())
.build();
}
}
基于 HttpClient 的客户端
使用Spring-AI-starter-mcp-client,配置一个McpSyncHttpClientRequestCustomizer豆:
@Configuration
class McpConfiguration {
@Bean
McpSyncClientCustomizer syncClientCustomizer() {
return (name, syncSpec) ->
syncSpec.transportContextProvider(
new AuthenticationMcpTransportContextProvider()
);
}
@Bean
McpSyncHttpClientRequestCustomizer requestCustomizer(
OAuth2AuthorizedClientManager clientManager
) {
// The clientRegistration name, "authserver",
// must match the name in application.properties
return new OAuth2AuthorizationCodeSyncHttpRequestCustomizer(
clientManager,
"authserver"
);
}
}
可用的定制器:
-
OAuth2AuthorizationCodeSyncHttpRequestCustomizer- 用于授权码流程 -
OAuth2ClientCredentialsSyncHttpRequestCustomizer- 用于客户端凭证流程 -
OAuth2HybridSyncHttpRequestCustomizer- 混合流
基于WebClient的客户端
使用Spring-AI-starter-mcp-client-webflux,配置一个WebClient.Builder配备MCP交换滤波函数:
@Configuration
class McpConfiguration {
@Bean
McpSyncClientCustomizer syncClientCustomizer() {
return (name, syncSpec) ->
syncSpec.transportContextProvider(
new AuthenticationMcpTransportContextProvider()
);
}
@Bean
WebClient.Builder mcpWebClientBuilder(OAuth2AuthorizedClientManager clientManager) {
// The clientRegistration name, "authserver", must match the name in application.properties
return WebClient.builder().filter(
new McpOAuth2AuthorizationCodeExchangeFilterFunction(
clientManager,
"authserver"
)
);
}
}
可用的过滤功能:
-
McpOAuth2AuthorizationCodeExchangeFilterFunction- 用于授权码流程 -
McpOAuth2ClientCredentialsExchangeFilterFunction- 用于客户端凭证流程 -
McpOAuth2HybridExchangeFilterFunction- 混合流
如何绕过 Spring AI 自动配置
Spring AI 的自动配置在启动时初始化 MCP 客户端,这可能导致基于用户的身份验证出现问题。为了避免这种情况:
选项1:禁用@Tool自动配置
禁用Spring AI@Tool通过发布一个空字段实现自动配置ToolCallbackResolver豆:
@Configuration
public class McpConfiguration {
@Bean
ToolCallbackResolver resolver() {
return new StaticToolCallbackResolver(List.of());
}
}
选项2:程序化客户端配置
通过程序化配置MCP客户端,而不是使用Spring Boot属性。对于基于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();
}
对于基于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();
}
然后把客户端添加到你的聊天客户端:
var chatResponse = chatClient.prompt("Prompt the LLM to do the thing")
.toolCallbacks(new SyncMcpToolCallbackProvider(mcpClient1, mcpClient2, mcpClient3))
.call()
.content();
MCP 授权服务器
MCP 授权服务器模块增强了 Spring Security 的 OAuth 2.0 授权服务器,增加了与 MCP 授权规范相关的功能,如动态客户端注册和资源指示器。
依赖
-
Maven
-
Gradle
<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
然后通过安全过滤链激活授权服务器功能:
@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();
}