Skip to content
Spring AI 文档版本 2.1.0-SNAPSHOT 源快照 bdf0d8ae 更新于 2026-10-16

MCP 安全

NOTE

这仍在进行之中。文档与 API 可能在未来版本中变更。

Spring AI MCP 安全模块为 Spring AI 中的模型上下文协议实现提供全面的 OAuth 2.0 与基于 API 密钥的安全支持。这个社区驱动的项目让开发者能用行业标准的认证与授权机制来保护 MCP 服务端和客户端。

NOTE

本模块是 spring-ai-community/mcp-security 项目的一部分。

这是一个社区驱动的项目,尚未获 Spring AI 或 MCP 项目的官方认可。查阅项目仓库以了解最新受支持的 Spring AI 版本。

概述

MCP 安全模块提供三个主要组件:

  • MCP 服务端安全 - 为 Spring AI MCP 服务端提供 OAuth 2.0 资源服务器与 API 密钥认证
  • MCP 客户端安全 - 为 Spring AI MCP 客户端提供 OAuth 2.0 客户端支持
  • MCP 授权服务器 - 带 MCP 专有能力、增强版的 Spring 授权服务器

该项目让开发者能够:

  • 用 OAuth 2.0 认证和基于 API 密钥的访问保护 MCP 服务端
  • 用 OAuth 2.0 授权流配置 MCP 客户端
  • 搭建专为 MCP 工作流设计的授权服务器
  • 为 MCP 工具与资源实现细粒度的访问控制

MCP 服务端安全

MCP 服务端安全模块为 Spring AI 的 MCP 服务端 提供 OAuth 2.0 资源服务器能力。 它还提供基于 API 密钥认证的基础支持。

WARNING

本模块仅兼容基于 Spring WebMVC 的服务端。

依赖

把以下依赖添加到你的项目:

xml
<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>

OAuth 2.0 配置

基本的 OAuth 2.0 设置

首先,在你的 application.properties 中启用 MCP 服务端:

properties
spring.ai.mcp.server.name=my-cool-mcp-server
# Supported protocols: STREAMABLE, STATELESS
spring.ai.mcp.server.protocol=STREAMABLE

然后,用 Spring Security 的标准 API 连同所提供的 MCP configurer 配置安全:

java
@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 操作(如 initialize 和 tools/list)保持公开:

java
@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 注解配合方法安全 来保护你的工具调用:

java
@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);
        };
    }
}

你也可以用 SecurityContextHolder 直接从工具方法访问当前的认证:

java
@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 提供了一个示例实现:

DANGER

InMemoryApiKeyEntityRepository 使用 bcrypt 存储 API 密钥,这在计算上开销很大。它不适合高流量的生产使用。对于生产,请实现你自己的 ApiKeyEntityRepository。

java
@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));
    }
}

借助此配置,你可以用一个头 X-API-key: api01.mycustomapikey 调用你的 MCP 服务端。

已知限制

WARNING

  • 不支持已弃用的 SSE 传输。请使用 Streamable HTTP 或无状态传输。
  • 不支持基于 WebFlux 的服务端。
  • 不支持不透明令牌。请使用 JWT。

MCP 客户端安全

MCP 客户端安全模块为 Spring AI 的 MCP 客户端 提供 OAuth 2.0 支持,同时支持基于 HttpClient 的客户端(来自 spring-ai-starter-mcp-client)和基于 WebClient 的客户端(来自 spring-ai-starter-mcp-client-webflux)。

WARNING

本模块仅支持 McpSyncClient。

依赖

xml
<dependency>
    <groupId>org.springaicommunity</groupId>
    <artifactId>mcp-client-security</artifactId>
</dependency>

授权流

有三种 OAuth 2.0 流可用于获取令牌:

  • 授权码流 - 用于每个 MCP 请求都在用户请求上下文中发起时的用户级权限
  • 客户端凭据流 - 用于没有人类参与的机器对机器用例
  • 混合流 - 结合两种流,用于某些操作(如 initialize 或 tools/list)在无用户在座时发生、但工具调用需要用户级权限的场景

TIP

当你有用户级权限且所有 MCP 请求都在用户上下文中发生时,使用授权码流。机器对机器通信使用客户端凭据流。当用 Spring Boot 属性配置 MCP 客户端时使用混合流,因为工具发现在无用户在座时的启动阶段发生。

DANGER

这些流会为每个出站 HTTP 请求附加一个逐请求令牌,但它们不会给每个用户各自的 MCP 协议会话。 自动配置的 MCP 客户端是应用作用域的单例,而有状态传输会在客户端 bean 的整个生命周期内保持其 Mcp-Session-Id,因此该 bean 的所有用户共享一个 MCP 会话。 不要依赖 MCP 会话来隔离用户,也要确保你所调用的 MCP 服务端不这么做。 关于完整的含义及如何获得按用户的协议隔离,参见客户端作用域与会话边界。

通用设置

对所有流,在你的 application.properties 中激活 Spring Security 的 OAuth2 客户端支持:

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 客户端能力的配置类:

java
@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 bean:

java
@Configuration
class McpConfiguration {

    @Bean
    McpCustomizer<McpClient.SyncSpec> 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 时,用一个 MCP ExchangeFilterFunction 配置 WebClient.Builder:

java
@Configuration
class McpConfiguration {

    @Bean
    McpCustomizer<McpClient.SyncSpec> 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 客户端,这可能给用户基础的认证带来问题。为避免这一点:

选项一:禁用 @Tool 自动配置

通过发布一个空的 ToolCallbackResolver bean 来禁用 Spring AI 的 @Tool 自动配置:

java
@Configuration
public class McpConfiguration {

    @Bean
    ToolCallbackResolver resolver() {
        return new StaticToolCallbackResolver(List.of());
    }
}

选项二:编程式客户端配置

以编程方式配置 MCP 客户端,而非使用 Spring Boot 属性。对于基于 HttpClient 的客户端:

java
@Bean
McpSyncClient client(
        JsonMapper jsonMapper,
        McpSyncHttpClientRequestCustomizer requestCustomizer,
        McpClientCommonProperties commonProps
) {
    var transport = HttpClientStreamableHttpTransport.builder(mcpServerUrl)
            .clientBuilder(HttpClient.newBuilder())
            .jsonMapper(new JacksonMcpJsonMapper(jsonMapper))
            .httpRequestCustomizer(requestCustomizer)
            .build();

    var clientInfo = McpSchema.Implementation.builder("client-name", commonProps.getVersion()).build();

    return McpClient.sync(transport)
            .clientInfo(clientInfo)
            .requestTimeout(commonProps.getRequestTimeout())
            .transportContextProvider(new AuthenticationMcpTransportContextProvider())
            .build();
}

对于基于 WebClient 的客户端:

java
@Bean
McpSyncClient client(
        WebClient.Builder mcpWebClientBuilder,
        JsonMapper jsonMapper,
        McpClientCommonProperties commonProperties
) {
    var builder = mcpWebClientBuilder.baseUrl(mcpServerUrl);
    var transport = WebClientStreamableHttpTransport.builder(builder)
            .jsonMapper(new JacksonMcpJsonMapper(jsonMapper))
            .build();

    var clientInfo = McpSchema.Implementation.builder("clientName", commonProperties.getVersion()).build();

    return McpClient.sync(transport)
            .clientInfo(clientInfo)
            .requestTimeout(commonProperties.getRequestTimeout())
            .transportContextProvider(new AuthenticationMcpTransportContextProvider())
            .build();
}

然后把该客户端添加到你的聊天客户端:

java
var chatResponse = chatClient.prompt("Prompt the LLM to do the thing")
        .tools(new SyncMcpToolCallbackProvider(
                mcpClient1, mcpClient2, mcpClient3))
        .call()
        .content();

已知限制

WARNING

  • 不支持 Spring WebFlux 服务端。
  • Spring AI 自动配置在应用启动时初始化 MCP 客户端,为用户基础的认证需要变通方案。
  • 逐请求令牌不会创建按用户的 MCP 协议会话,因为会话属于共享的客户端 bean。 需要按用户协议隔离的应用必须自行管理客户端生命周期。
  • 与服务端模块不同,客户端实现同时支持基于 HttpClient 和 WebClient 的 SSE 传输。

MCP 授权服务器

MCP 授权服务器模块用与 MCP 授权规范 相关的能力(如动态客户端注册与资源标识符)增强了 Spring Security 的 OAuth 2.0 授权服务器。

依赖

xml
<dependency>
    <groupId>org.springaicommunity</groupId>
    <artifactId>mcp-authorization-server</artifactId>
</dependency>

配置

在你的 application.yml 中配置授权服务器:

yaml
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

然后用一个安全过滤器链激活授权服务器能力:

java
@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();
}

已知限制

WARNING

  • 不支持 Spring WebFlux 服务端。
  • 每个客户端支持所有 resource 标识符。

示例与集成

示例目录 为该项目的所有模块包含可运行的示例,包括集成测试。

借助 mcp-server-security 和一个配套的 mcp-authorization-server,你可以与以下集成:

NOTE

使用 MCP Inspector 时,你可能需要禁用 CSRF 与 CORS 保护。

其他资源

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。