Skip to content
Back to search

mcp-security

Spring Security Configuration for MCP

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/spring-ai-community/mcp-security with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/spring-ai-community/mcp-security'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/spring-ai-community--mcp-security/badge.svg)](/listings/spring-ai-community--mcp-security)

HTML

<a href="/listings/spring-ai-community--mcp-security"><img src="/api/listings/spring-ai-community--mcp-security/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

The easiest way to add OAuth2 security to your MCP server is with the Boot auto-configuration module. It provides a default `SecurityFilterChain` that secures all endpoints, with no additional configuration required beyond setting the issuer URI.

*Maven*


<dependencies>

    <dependency>
        <groupId>org.springaicommunity</groupId>
        <artifactId>mcp-server-security-spring-boot</artifactId>
        <version>0.1.14</version>
    </dependency>

</dependencies>

*Gradle*

implementation("org.springaicommunity:mcp-server-security-spring-boot:0.1.14")

Then configure your `application.properties`:

spring.ai.mcp.server.name=my-cool-mcp-server
spring.ai.mcp.server.protocol=STREAMABLE

# The issuer URI of the authorization server
spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:9000

That's it. When `spring.security.oauth2.resourceserver.jwt.issuer-uri` is set, the auto-configuration creates a `SecurityFilterChain` that secures all endpoints using the `McpServerOAuth2Configurer`.

For a complete working example, see the [sample-mcp-server](https://github.com/spring-ai-community/mcp-security/tree/main/samples/sample-mcp-server) module.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 1,270 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # MCP Security
  2. [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
  3. [![Java Version](https://img.shields.io/badge/Java-17%2B-orange)](https://www.oracle.com/java/technologies/javase/jdk17-archive-downloads.html)
  4. Security and Authorization support for Model Context Protocol in Spring AI.
  5. > ⚠️ Versions 0.1.x of `mcp-security` only work Spring AI's 2.0.x branch. For Spring AI 1.1.x, use version `0.0.6`.
  6. ## Table of Contents
  7. - [Overview](#overview)
  8. - [MCP Server Security](#mcp-server-security)
  9. - [MCP Client Security](#mcp-client-security)
  10. - [Authorization Server](#authorization-server)
  11. - [Samples](#samples)
  12. - [Integrations](#integrations) (Cursor, Claude Desktop, ...)
  13. - [License](#license)
  14. ## Overview
  15. This repository provides
  16. [Authorization](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization) support for
  17. Spring AI integrations with the Model Context Protocol (MCP). It covers both MCP Clients, MCP Servers, and Spring
  18. Authorization Server.
  19. The project enables developers to:
  20. - Secure MCP servers with OAuth 2.0 authentication
  21. - Configure MCP clients with OAuth 2.0 authorization flows
  22. - Set up authorization servers specifically designed for MCP workflows
  23. - Implement fine-grained access control for MCP tools and resources
  24. ## MCP Server Security
  25. Provides OAuth 2.0 resource server capabilities
  26. for [Spring AI's MCP servers](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-starter-docs.html).
  27. It also provides basic support for API-key based servers.
  28. OAuth2 and API-key authentication are compatible with Spring WebMVC-based servers only.
  29. [Origin validation](#origin-validation) additionally supports Spring WebFlux.
  30. ### Quick start with `mcp-server-security-spring-boot` (recommended)
  31. The easiest way to add OAuth2 security to your MCP server is with the Boot auto-configuration module.
  32. It provides a default `SecurityFilterChain` that secures all endpoints, with no additional configuration
  33. required beyond setting the issuer URI.
  34. *Maven*
  35. ```xml
  36. <dependencies>
  37. <dependency>
  38. <groupId>org.springaicommunity</groupId>
  39. <artifactId>mcp-server-security-spring-boot</artifactId>
  40. <version>0.1.14</version>
  41. </dependency>
  42. </dependencies>
  43. ```
  44. *Gradle*
  45. ```groovy
  46. implementation("org.springaicommunity:mcp-server-security-spring-boot:0.1.14")
  47. ```
  48. Then configure your `application.properties`:
  49. ```properties
  50. spring.ai.mcp.server.name=my-cool-mcp-server
  51. spring.ai.mcp.server.protocol=STREAMABLE
  52. # The issuer URI of the authorization server
  53. spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:9000
  54. ```
  55. That's it. When `spring.security.oauth2.resourceserver.jwt.issuer-uri` is set, the auto-configuration
  56. creates a `SecurityFilterChain` that secures all endpoints using the `McpServerOAuth2Configurer`.
  57. For a complete working example, see the
  58. [sample-mcp-server](https://github.com/spring-ai-community/mcp-security/tree/main/samples/sample-mcp-server) module.
  59. ### Manual setup with `mcp-server-security`
  60. If you prefer wiring beans yourself (e.g. for advanced customization, API key support, or non-Boot use-cases),
  61. you can use the lower-level `mcp-server-security` module directly.
  62. *Maven*
  63. ```xml
  64. <dependencies>
  65. <dependency>
  66. <groupId>org.springaicommunity</groupId>
  67. <artifactId>mcp-server-security</artifactId>
  68. <version>0.1.14</version>
  69. </dependency>
  70. <dependency>
  71. <groupId>org.springframework.boot</groupId>
  72. <artifactId>spring-boot-starter-security</artifactId>
  73. </dependency>
  74. <!-- OPTIONAL -->
  75. <!-- If you would like to use OAuth2, ensure you import the Resource Server dependencies -->
  76. <dependency>
  77. <groupId>org.springframework.boot</groupId>
  78. <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
  79. </dependency>
  80. </dependencies>
  81. ```
  82. *Gradle*
  83. ```groovy
  84. implementation("org.springaicommunity:mcp-server-security:0.1.14")
  85. implementation("org.springframework.boot:spring-boot-starter-security")
  86. // OPTIONAL
  87. // If you would like to use OAuth2, ensure you import the Resource Server dependencies
  88. implementation("org.springframework.boot:spring-boot-starter-oauth2-resource-server")
  89. ```
  90. ### Usage: OAuth2
  91. Ensure that MCP server is enabled in your `application.properties`:
  92. ```properties
  93. spring.ai.mcp.server.name=my-cool-mcp-server
  94. # Supported protocols: STREAMABLE, STATELESS
  95. spring.ai.mcp.server.protocol=STREAMABLE
  96. ```
  97. Then, configure the security for your project in the usual Spring-Security way, adding the provided configurer.
  98. Create a configuration class, and reference the authorization server's URI.
  99. In this example, we have set the authz server's issuer URI in the well known Spring property
  100. `spring.security.oauth2.resourceserver.jwt.issuer-uri`.
  101. Using this exact name is not a requirement, and you may use a custom property.
  102. ```java
  103. @Configuration
  104. @EnableWebSecurity
  105. class McpServerConfiguration {
  106. @Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
  107. private String issuerUrl;
  108. @Bean
  109. SecurityFilterChain securityFilterChain(HttpSecurity http) {
  110. return http
  111. // Enforce authentication with token on EVERY request
  112. .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
  113. // Configure OAuth2 on the MCP server
  114. .with(
  115. McpServerOAuth2Configurer.mcpServerOAuth2(),
  116. (mcpAuthorization) -> {
  117. // REQUIRED: the issuerURI
  118. mcpAuthorization.authorizationServer(issuerUrl);
  119. // OPTIONAL: enforce the `aud` claim in the JWT token.
  120. // Not all authorization servers support resource indicators,
  121. // so it may be absent. Defaults to `false`.
  122. // See RFC 8707 Resource Indicators for OAuth 2.0
  123. // https://www.rfc-editor.org/rfc/rfc8707.html
  124. //
  125. // mcpAuthorization.validateAudienceClaim(true);
  126. // OPTIONAL: bind the MCP session to the user's identity
  127. // This ensures that a session created by a user can only be accessed by that user
  128. //
  129. // mcpAuthorization.sessionBinding(Customizer.withDefaults());
  130. }
  131. )
  132. .build();
  133. }
  134. }
  135. ```
  136. ### Special case: only secure tool calls with OAuth2
  137. It is also possible to secure the tools only, and not the rest of the MCP Server. For example, both `initialize` and
  138. `tools/list` are made public, but `tools/call` is authenticated.
  139. To enable this, update the security configuration, turn on method security and requests to `/mcp` are allowed:
  140. ```java
  141. @Configuration
  142. @EnableWebSecurity
  143. @EnableMethodSecurity // ⬅️ enable annotation-driven security
  144. class McpServerConfiguration {
  145. @Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
  146. private String issuerUrl;
  147. @Bean
  148. SecurityFilterChain securityFilterChain(HttpSecurity http) {
  149. return http
  150. // ⬇️ Open every request on the server
  151. .authorizeHttpRequests(auth -> {
  152. auth.requestMatchers("/mcp").permitAll();
  153. auth.anyRequest().authenticated();
  154. })
  155. // Configure OAuth2 on the MCP server
  156. .with(
  157. McpServerOAuth2Configurer.mcpServerOAuth2(),
  158. (mcpAuthorization) -> {
  159. // REQUIRED: the issuerURI
  160. mcpAuthorization.authorizationServer(issuerUrl);
  161. }
  162. )
  163. .build();
  164. }
  165. }
  166. ```
  167. Then, secure your tool calls using the `@PreAuthorize` annotation,
  168. using [method security](https://docs.spring.io/spring-security/reference/servlet/authorization/method-security.html).
  169. Inside the annotation, you can apply
  170. a [security-based SpEL expression](https://docs.spring.io/spring-security/reference/servlet/authorization/method-security.html#using-authorization-expression-fields-and-methods).
  171. At the most basic level, you can use `isAuthenticated()`, ensuring that the MCP client sent a request with a valid
  172. bearer token:
  173. ```java
  174. @Service
  175. public class MyToolsService {
  176. // Note: you can also use Spring AI's @Tool
  177. @PreAuthorize("isAuthenticated()")
  178. @McpTool(name = "greeter", description = "A tool that greets you, in the selected language")
  179. public String greet(
  180. @McpToolParam(description = "The language for the greeting (example: english, french, ...)") String language
  181. ) {
  182. if (!StringUtils.hasText(language)) {
  183. language = "";
  184. }
  185. return switch (language.toLowerCase()) {
  186. case "english" -> "Hello you!";
  187. case "french" -> "Salut toi!";
  188. default -> "I don't understand language \"%s\". So I'm just going to say Hello!".formatted(language);
  189. };
  190. }
  191. }
  192. ```
  193. Note that you can also access the current authentication directly from the tool method itself, using the thread-local
  194. `SecurityContextHolder`:
  195. ```java
  196. @McpTool(name = "greeter", description = "A tool that greets the user by name, in the selected language")
  197. @PreAuthorize("isAuthenticated()")
  198. public String greet(
  199. @McpToolParam(description = "The language for the greeting (example: english, french, ...)") String language
  200. ) {
  201. if (!StringUtils.hasText(language)) {
  202. language = "";
  203. }
  204. var authentication = SecurityContextHolder.getContext().getAuthentication();
  205. var name = authentication.getName();
  206. return switch (language.toLowerCase()) {
  207. case "english" -> "Hello, %s!".formatted(name);
  208. case "french" -> "Salut %s!".formatted(name);
  209. default -> ("I don't understand language \"%s\". " +
  210. "So I'm just going to say Hello %s!").formatted(language, name);
  211. };
  212. }
  213. ```
  214. ### Usage: API keys
  215. Ensure that MCP server is enabled in your `application.properties`:
  216. ```properties
  217. spring.ai.mcp.server.name=my-cool-mcp-server
  218. # Supported protocols: STREAMABLE, STATELESS
  219. spring.ai.mcp.server.protocol=STREAMABLE
  220. ```
  221. For this, you'll need to provide your own implementation of `ApiKeyEntityRepository`, for storing `ApiKeyEntity`
  222. objects.
  223. These represent the "entities" which have API keys.
  224. Each entry has an ID, a secret for storing API keys in a secure way (e.g. bcrypt, argon2, ...), as well as a name used
  225. for display purposes.
  226. A sample implementation is available with an `InMemoryApiKeyEntityRepository` along with a default `ApiKeyEntityImpl`.
  227. You can bring your own entity implementation with the in-memory repository.
  228. > ⚠️ The `InMemoryApiKeyEntityRepository` uses on bcrypt for storing the API keys, and, as such, will be computationally
  229. > expensive. It is not suited for high-traffic production use. In that case, you must ship your own
  230. > `ApiKeyEntityRepository` implementation.
  231. With that, you can configure the security for your project in the usual Spring-Security way:
  232. ```java
  233. @Configuration
  234. @EnableWebSecurity
  235. class McpServerConfiguration {
  236. @Bean
  237. SecurityFilterChain securityFilterChain(HttpSecurity http) {
  238. return http.authorizeHttpRequests(authz -> authz.anyRequest().authenticated())
  239. .with(
  240. mcpServerApiKey(),
  241. (apiKey) -> {
  242. // REQUIRED: the repo for API keys
  243. apiKey.apiKeyRepository(apiKeyRepository());
  244. // OPTIONAL: name of the header containing the API key.
  245. // Here for example, api keys will be sent with "CUSTOM-API-KEY: <value>"
  246. // Replaces .authenticationConverter(...) (see below)
  247. //
  248. // apiKey.headerName("CUSTOM-API-KEY");
  249. // OPTIONAL: custom converter for transforming an http request
  250. // into an authentication object. Useful when the header is
  251. // "Authorization: Bearer <value>".
  252. // Replaces .headerName(...) (see above)
  253. //
  254. // apiKey.authenticationConverter(request -> {
  255. // var key = extractKey(request);
  256. // return ApiKeyAuthenticationToken.unauthenticated(key);
  257. // });
  258. // OPTIONAL: bind the MCP session to the user's identity
  259. // This ensures that a session created with a given API key
  260. // can only be used with that API key
  261. //
  262. // apiKey.sessionBinding(Customizer.withDefaults());
  263. }
  264. )
  265. .build();
  266. }
  267. /**
  268. * Provide a repository of {@link ApiKeyEntity}.
  269. */
  270. private ApiKeyEntityRepository<ApiKeyEntityImpl> apiKeyRepository() {
  271. //@formatter:off
  272. var apiKey = ApiKeyEntityImpl.builder()
  273. .name("test api key")
  274. .id("api01")
  275. .secret("mycustomapikey")
  276. .build();
  277. //@formatter:on
  278. return new InMemoryApiKeyEntityRepository<>(List.of(apiKey));
  279. }
  280. }
  281. ```
  282. Then you should be able to call your MCP server with a header `X-API-key: api01.mycustomapikey`.
  283. Requests without an API key receive an HTTP 401 response when no other configured authentication mechanism
  284. authenticates the request. Requests containing an invalid API key also receive an HTTP 401 response.
  285. ### Origin validation
  286. MCP servers that listen on localhost are reachable from any web page the user visits, which makes them a target for
  287. DNS rebinding attacks. To mitigate this, the
  288. [MCP specification](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#security-warning)
  289. requires servers to validate the `Origin` header of incoming requests.
  290. Unlike the rest of MCP Server Security, origin validation works on both Spring WebMVC and Spring WebFlux servers.
  291. With `mcp-server-security-spring-boot`, origin validation is **on by default**, and allows local origins only:
  292. ```yaml
  293. spring:
  294. ai:
  295. mcp:
  296. server:
  297. security:
  298. # Defaults to http://localhost:*, http://127.0.0.1:*, http://[::1]:*, http://[::]:*
  299. allowed-origins:
  300. - https://mcp-client.example.com
  301. - https://another-mcp-client.example.com:*
  302. # OPTIONAL: also validate the Host header. Not validated by default.
  303. allowed-hosts:
  304. - mcp-server.example.com
  305. - mcp-server.example.com:*
  306. ```
  307. Setting `allowed-origins` replaces the defaults, so remember to add back the local origins if you still need them, for
  308. example when developing with the MCP Inspector.
  309. #### WebMVC servers
  310. When wiring things up manually with `mcp-server-security`, validation is **not** enabled unless you configure it, on
  311. either configurer:
  312. ```java
  313. http.with(mcpServerOAuth2(), (mcpAuthorization) -> {
  314. mcpAuthorization.authorizationServer(issuerUrl);
  315. // OPTIONAL: restrict the Origin header
  316. mcpAuthorization.allowedOrigins(List.of("https://mcp-client.example.com"));
  317. // OPTIONAL: restrict the Host header
  318. mcpAuthorization.allowedHosts(List.of("mcp-server.example.com"));
  319. });
  320. // ... or, for API-key based servers:
  321. http.with(mcpServerApiKey(), (apiKey) -> {
  322. apiKey.apiKeyRepository(apiKeyRepository());
  323. apiKey.allowedOrigins(List.of("https://mcp-client.example.com"));
  324. apiKey.allowedHosts(List.of("mcp-server.example.com"));
  325. });
  326. ```
  327. Both origins and hosts support exact matches and wildcard port patterns (`https://example.com:*`, `example.com:*`).
  328. Rejected requests receive a JSON-RPC error body, with an HTTP 403 for a disallowed `Origin` and an HTTP 421 for a disallowed `Host`.
  329. If your server needs to support Cross-Origin requests (CORS), see CORS support in Spring Security
  330. for [servlet](https://docs.spring.io/spring-security/reference/servlet/integrations/cors.html)
  331. applications.
  332. #### WebFlux servers
  333. When wiring things up manually with `mcp-server-security`, add the `OriginValidationWebFilter` to your
  334. `ServerHttpSecurity`:
  335. ```java
  336. @Bean
  337. SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
  338. // The second argument is the OPTIONAL Host allowlist; pass null to skip Host validation
  339. var originValidation = new OriginValidationWebFilter(
  340. List.of("https://mcp-client.example.com"),
  341. List.of("mcp-server.example.com"));
  342. return http.authorizeExchange(exchanges -> exchanges.anyExchange().authenticated())
  343. .addFilterAfter(originValidation, SecurityWebFiltersOrder.CORS)
  344. .build();
  345. }
  346. ```
  347. Both origins and hosts support exact matches and wildcard port patterns (`https://example.com:*`, `example.com:*`).
  348. Rejected requests receive a JSON-RPC error body, with an HTTP 403 for a disallowed `Origin` and an HTTP 421 for a disallowed `Host`.
  349. If your server needs to support Cross-Origin requests (CORS), see CORS support in Spring Security
  350. for [reactive](https://docs.spring.io/spring-security/reference/reactive/integrations/cors.html) applications.
  351. ### Known limitations
  352. - The deprecated SSE transport is not supported.
  353. Use [Streamable HTTP](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#streamable-http)
  354. or [stateless transport](https://modelcontextprotocol.io/sdk/java/mcp-server#stateless-streamable-http-webmvc). (the
  355. link for stateless does not work out of the box, reload the page if required)
  356. - WebFlux-based servers are only supported for [origin validation](#origin-validation). OAuth2 and API-key
  357. authentication require WebMVC.
  358. - Opaque tokens are not supported. Use JWT.
  359. ## MCP Client Security
  360. Provides OAuth 2 support
  361. for [Spring AI's MCP clients](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-client-boot-starter-docs.html).
  362. This module supports `McpSyncClient`s only, with HttpClient-based clients (from `spring-ai-starter-mcp-client`) and
  363. WebClient-based clients (from `spring-ai-starter-mcp-client-webflux`).
  364. Key features:
  365. - OAuth2 `authorization_code`, `client_credentials`, and hybrid flows
  366. - Dynamic Client Registration (DCR) with automatic MCP server metadata discovery
  367. - Client ID Metadata Document (CIMD): alternative to DCR where the client hosts its own metadata document
  368. - Scope step-up: automatic re-authorization when the MCP server requires additional scopes
  369. - Spring Boot auto-configuration via `mcp-client-security-spring-boot`
  370. ### Quick start with `mcp-client-security-spring-boot` (recommended)
  371. The easiest way to add OAuth2 support to your MCP clients is with the Boot auto-configuration module.
  372. *Maven*
  373. ```xml
  374. <dependencies>
  375. <dependency>
  376. <groupId>org.springaicommunity</groupId>
  377. <artifactId>mcp-client-security-spring-boot</artifactId>
  378. <version>0.1.14</version>
  379. </dependency>
  380. <dependency>
  381. <groupId>org.springframework.ai</groupId>
  382. <artifactId>spring-ai-starter-mcp-client</artifactId>
  383. </dependency>
  384. </dependencies>
  385. ```
  386. *Gradle*
  387. ```groovy
  388. implementation("org.springaicommunity:mcp-client-security-spring-boot:0.1.14")
  389. implementation("org.springframework.ai:spring-ai-starter-mcp-client")
  390. ```
  391. Configure your MCP client connections in `application.properties`:
  392. ```properties
  393. spring.ai.mcp.client.type=SYNC
  394. spring.ai.mcp.client.initialized=false
  395. # MCP server connections (Spring AI auto-configures these)
  396. spring.ai.mcp.client.streamable-http.connections.my-mcp-server.url=http://localhost:8090
  397. # Enable Dynamic Client Registration (default: false)
  398. spring.ai.mcp.client.authorization.dynamic-client-registration.enabled=true
  399. # For development purposes, allow loopback addresses for MCP Servers and Auth Servers (default: false)
  400. spring.ai.mcp.client.authorization.dynamic-client-registration.allow-loopback-addresses=true
  401. ```
  402. Then, configure a `SecurityFilterChain` with the provided `McpClientOAuth2Configurer`:
  403. ```java
  404. @Configuration
  405. @EnableWebSecurity
  406. class SecurityConfiguration {
  407. @Bean
  408. SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  409. return http
  410. .authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
  411. .with(McpClientOAuth2Configurer.mcpClientOAuth2(), Customizer.withDefaults())
  412. .csrf(CsrfConfigurer::disable)
  413. .build();
  414. }
  415. }
  416. ```
  417. This is all you need. The auto-configuration module sets up the following beans:
  418. - `McpClientRegistrationRepository`: a `ClientRegistrationRepository` that also tracks the associated MCP resource
  419. identifier
  420. - `McpOAuth2ClientManager`: manages Dynamic Client Registration (DCR) and scope step-up
  421. - `UrlValidator`, `McpMetadataDiscoveryService` and `DynamicClientRegistrationService`: infrastructure for DCR
  422. - Various `McpClientConfigurer` to update MCP transports and MCP clients so a token is added on every request
  423. For a complete working example, see the
  424. [sample-mcp-client](https://github.com/spring-ai-community/mcp-security/tree/main/samples/sample-mcp-client) module.
  425. ### Manual setup with `mcp-client-security`
  426. If you prefer wiring beans yourself (e.g. for advanced or non-Boot use-cases), you can use the lower-level
  427. `mcp-client-security` module directly.
  428. *Maven*
  429. ```xml
  430. <dependency>
  431. <groupId>org.springaicommunity</groupId>
  432. <artifactId>mcp-client-security</artifactId>
  433. <version>0.1.14</version>
  434. </dependency>
  435. ```
  436. *Gradle*
  437. ```groovy
  438. implementation("org.springaicommunity:mcp-client-security:0.1.14")
  439. ```
  440. ### Authorization flows
  441. For MCP clients, there are three flows available for obtaining tokens:
  442. - `authorization_code`-based flows. This is the flow that the MCP spec illustrates.
  443. A user is present, and the MCP client makes HTTP requests using a bearer token on behalf of that user.
  444. - `client_credentials`-based flows. This is not detailed in the spec, but compatible.
  445. Client credentials is for machine-to-machine use-cases, where there is no human in the loop.
  446. The MCP client makes HTTP requests with a token for itself.
  447. - Hybrid flows. In some use-cases, the user might not be present for some MCP client calls, such
  448. as `initialize` or `tools/list`.
  449. In that case, the MCP client makes calls with `client_credentials` tokens representing the client itself.
  450. But the user may be present for `tools/call`, and in that case, the client will use an `authorization_code` token
  451. representing the user.
  452. 🤔 Which flow should I use?
  453. - If there are user-level permissions, AND you know every MCP request will be made within the context of a user request
  454. (ensure there are no `tools/list` calls on app startup), then use the `authorization_code` flow.
  455. - If there are no user-level permissions, and you want to secure "client-to-server" communication with an access token,
  456. use the `client_credentials` flow.
  457. - If there are user-level permissions, AND you configure your MCP clients using Spring Boot properties (such as
  458. `spring.ai.mcp.client.streamable-http.connections.<server-name>.url=<server-url>`), then, on application startup,
  459. Spring AI will try to list the tools. And startup happens without a user present. In that specific case, use a hybrid
  460. flow.
  461. ### Dynamic Client Registration (DCR)
  462. MCP Security supports
  463. [RFC 7591 Dynamic Client Registration](https://www.rfc-editor.org/rfc/rfc7591.html) as described in the
  464. [MCP Authorization spec](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization).
  465. When enabled, the flow works as follows:
  466. 1. The MCP client sends a request to the MCP server without a token.
  467. 2. The server responds with HTTP 401 and a `WWW-Authenticate` header containing the resource metadata URL.
  468. 3. The `OAuth2SyncAuthorizationErrorHandler` fetches the protected resource metadata and discovers the authorization
  469. server.
  470. 4. The handler performs dynamic client registration with the authorization server.
  471. 5. If the server later responds with HTTP 403 and `insufficient_scope`, the handler requests the additional scopes
  472. (scope step-up).
  473. DCR is disabled by default in the `mcp-client-security-spring-boot` auto-configuration.
  474. To enable it, set `spring.ai.mcp.client.authorization.dynamic-client-registration.enabled=true`.
  475. When disabled, ensure you either have a single `ClientRegistration` registered under
  476. `spring.security.oauth2.client.registration`, or provide your own `OAuth2HttpClientTransportCustomizer` bean.
  477. Scope step-up is still supported when DCR is disabled.
  478. #### URL Validation
  479. As a security measure to prevent Server-Side Request Forgery (SSRF), MCP Security enforces HTTPS for all URLs involved
  480. in the Dynamic Client Registration flow, including the resource metadata URL and the authorization server endpoints.
  481. This validation is provided by the `UrlValidator` interface and its implementation.
  482. For production use-cases, tailor the SSRF checks to your specific network setup with a custom implementation of
  483. `UrlValidator`.
  484. When using `mcp-client-security-spring-boot`, when running in development mode, you may need to allow HTTP urls. You can
  485. explicitly allow HTTP for loopback addresses (like `localhost`, `127.0.0.1`, and `[::1]`) by setting the following
  486. property:
  487. ```properties
  488. spring.ai.mcp.client.authorization.dynamic-client-registration.allow-loopback-addresses=true
  489. ```
  490. ### Client ID Metadata Document (CIMD)
  491. CIMD is an alternative to DCR where the client uses a URL as its `client_id`. This URL points to a JSON
  492. metadata document hosted by the client itself. The authorization server fetches that document when processing
  493. an authorization request.
  494. There is no auto-configuration support for CIMD, so you need to manually declare a filter chain, and add the supporting
  495. beans explicilty.
  496. Add `McpClientOAuth2Configurer` to your security filter chain with CIMD enabled (this is the default):
  497. ```java
  498. @Bean
  499. SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  500. return http
  501. .authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
  502. .with(new McpClientOAuth2Configurer(), mcp -> mcp.cimd(true))
  503. .build();
  504. }
  505. ```
  506. This registers a filter that serves the client metadata document at `/{registrationId}/client-id-metadata.json`, valid for any `{registrationId}`.
  507. Then declare a `DefaultMcpOAuth2CimdClientManager` bean and use `OAuth2CimdHttpClientTransportCustomizer`
  508. instead of the DCR variant:
  509. ```java
  510. @Bean
  511. McpOAuth2CimdClientManager cimdClientManager(
  512. McpMetadataDiscoveryService discoveryService,
  513. McpClientRegistrationRepository repo,
  514. UrlValidator urlValidator) {
  515. return new DefaultMcpOAuth2CimdClientManager(discoveryService, repo, urlValidator);
  516. }
  517. @Bean
  518. McpClientCustomizer<HttpClientStreamableHttpTransport.Builder> transportCustomizer(
  519. OAuth2AuthorizedClientManager authorizedClientManager,
  520. McpClientRegistrationRepository repo,
  521. McpOAuth2CimdClientManager cimdClientManager) {
  522. return new OAuth2CimdHttpClientTransportCustomizer(authorizedClientManager, repo, cimdClientManager);
  523. }
  524. ```
  525. ### Use with `McpClientOAuth2Configurer`
  526. `McpClientOAuth2Configurer` is a Spring Security configurer that sets up OAuth2 client support for MCP,
  527. including authorization request and token request customization (e.g. adding the `resource=` parameter).
  528. You can also use it to pre-register OAuth2 clients for specific MCP servers:
  529. ```java
  530. @Configuration
  531. @EnableWebSecurity
  532. class SecurityConfiguration {
  533. @Bean
  534. SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  535. return http
  536. .authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
  537. .with(McpClientOAuth2Configurer.mcpClientOAuth2(), mcpOAuth2 -> {
  538. // Pre-register an OAuth2 client for a specific MCP server
  539. mcpOAuth2.registerMcpOAuth2Client("my-mcp-server", "http://localhost:8090/mcp");
  540. // Optionally set the base URL for redirect URIs
  541. // mcpOAuth2.baseUrl("http://localhost:8080");
  542. })
  543. .build();
  544. }
  545. }
  546. ```
  547. ### Use with `spring-ai-starter-mcp-client` (HttpClient-based)
  548. When using `spring-ai-starter-mcp-client`, the underlying MCP client transport is based on the JDK's
  549. `HttpClient`.
  550. **With auto-configuration (`mcp-client-security-spring-boot`):**
  551. The `OAuth2HttpClientTransportCustomizer` is auto-configured and applies OAuth2 support
  552. (request customization and authorization error handling) to each transport automatically. No extra beans are needed.
  553. **Manual configuration:**
  554. You can expose an `OAuth2HttpClientTransportCustomizer` bean, which configures both the request customizer
  555. and the authorization error handler on each transport:
  556. ```java
  557. @Configuration
  558. class McpConfiguration {
  559. @Bean
  560. OAuth2HttpClientTransportCustomizer transportCustomizer(
  561. OAuth2AuthorizedClientManager clientManager,
  562. ClientRegistrationRepository clientRegistrationRepository,
  563. McpOAuth2ClientManager mcpOAuth2ClientManager
  564. ) {
  565. return new OAuth2HttpClientTransportCustomizer(
  566. clientManager,
  567. clientRegistrationRepository,
  568. mcpOAuth2ClientManager
  569. );
  570. }
  571. }
  572. ```
  573. By default, the customizer maps each MCP connection name to an OAuth2 client registration with the same name.
  574. You can customize this mapping:
  575. ```java
  576. // Use a single registration for all transports
  577. new OAuth2HttpClientTransportCustomizer(clientManager, repo, mcpManager, "my-registration-id");
  578. // Or use a custom resolver function
  579. new OAuth2HttpClientTransportCustomizer(clientManager, repo, mcpManager, transportName -> "prefix-" + transportName);
  580. ```
  581. Alternatively, if you do not need DCR or authorization error handling, you can use the lower-level
  582. request customizers directly:
  583. - `OAuth2AuthorizationCodeSyncHttpRequestCustomizer` (user-level tokens)
  584. - `OAuth2ClientCredentialsSyncHttpRequestCustomizer` (machine-to-machine)
  585. - `OAuth2HybridSyncHttpRequestCustomizer` (both)
  586. All request customizers rely on authentication data passed through `McpTransportContext`.
  587. When not using the Boot auto-configuration, you need to add an `AuthenticationMcpTransportContextProvider`:
  588. ```java
  589. @Configuration
  590. class McpConfiguration {
  591. @Bean
  592. McpSyncClientCustomizer syncClientCustomizer() {
  593. return (name, syncSpec) ->
  594. syncSpec.transportContextProvider(
  595. new AuthenticationMcpTransportContextProvider()
  596. );
  597. }
  598. @Bean
  599. McpSyncHttpClientRequestCustomizer requestCustomizer(
  600. OAuth2AuthorizedClientManager clientManager,
  601. ClientRegistrationRepository clientRegistrationRepository
  602. ) {
  603. return new OAuth2AuthorizationCodeSyncHttpRequestCustomizer(
  604. clientManager,
  605. clientRegistrationRepository,
  606. "authserver"
  607. );
  608. }
  609. }
  610. ```
  611. ### Use with `spring-ai-starter-mcp-client-webflux`
  612. When using `spring-ai-starter-mcp-client-webflux`, the underlying MCP client transport will be based on a Spring
  613. reactive `WebClient`.
  614. In that case, you can expose a bean of type `WebClient.Builder`, configured with an MCP implementation of
  615. `ExchangeFilterFunction`.
  616. Depending on your [authorization flow](#authorization-flows) of choice, you may use one of the following
  617. implementations:
  618. - `McpOAuth2AuthorizationCodeExchangeFilterFunction` (preferred)
  619. - `McpOAuth2ClientCredentialsExchangeFilterFunction` (machine-to-machine)
  620. - `McpOAuth2HybridExchangeFilterFunction` (last resort)
  621. All these filter functions rely on authentication data passed through `McpTransportContext`.
  622. When not using the Boot auto-configuration, you need to add an `AuthenticationMcpTransportContextProvider`:
  623. ```java
  624. @Configuration
  625. class McpConfiguration {
  626. @Bean
  627. McpSyncClientCustomizer syncClientCustomizer() {
  628. return (name, syncSpec) ->
  629. syncSpec.transportContextProvider(
  630. new AuthenticationMcpTransportContextProvider()
  631. );
  632. }
  633. @Bean
  634. WebClient.Builder mcpWebClientBuilder(OAuth2AuthorizedClientManager clientManager) {
  635. return WebClient.builder().filter(
  636. new McpOAuth2AuthorizationCodeExchangeFilterFunction(
  637. clientManager,
  638. "authserver"
  639. )
  640. );
  641. }
  642. }
  643. ```
  644. ### Use with streaming chat client
  645. When using the `.stream()` method of the chat client, you will be using Reactor under the hood. Reactor does not
  646. guarantee on which thread the work is executed, and will lose thread locals. You need to manually extract the
  647. information and inject it in the Reactor context:
  648. ```java
  649. class Example {
  650. void doTheThing() {
  651. chatClient
  652. .prompt("<your prompt>")
  653. .stream()
  654. .content()
  655. // ... any streaming operation ...
  656. .contextWrite(AuthenticationMcpTransportContextProvider.writeToReactorContext());
  657. }
  658. }
  659. ```
  660. ### Customize HTTP requests beyond MCP Security's OAuth2 support
  661. MCP Security's default client support integrates with Spring Security to add OAuth2 support. Essentially, it gets a
  662. token on behalf of the user, and modifies the HTTP request from the Client to the Server, adding that token in an
  663. Authorization header.
  664. If you'd like to modify HTTP requests beyond what MCP Security provides, you can create your own
  665. `McpSyncHttpClientRequestCustomizer` or `ExchangeFilterFunction`.
  666. For HTTP clients:
  667. ```java
  668. @Configuration
  669. class McpConfiguration {
  670. @Bean
  671. McpSyncHttpClientRequestCustomizer requestCustomizer() {
  672. return (builder, method, endpoint, body, context) ->
  673. builder
  674. .header("x-custom-header", "custom-value")
  675. .header("x-life-the-universe-everything", "42");
  676. }
  677. }
  678. ```
  679. For web clients:
  680. ```java
  681. @Configuration
  682. class McpConfiguration {
  683. @Bean
  684. WebClient.Builder mcpWebClientBuilder() {
  685. return WebClient.builder().filter((request, next) -> {
  686. var newRequest = ClientRequest.from(request)
  687. .header("x-custom-header", "custom-value")
  688. .header("x-life-the-universe-everything", "42")
  689. .build();
  690. return next.exchange(newRequest);
  691. });
  692. }
  693. }
  694. ```
  695. There is no way to guarantee on which thread these request customizers will run.
  696. As such, thread-locals are not available in these lambda functions.
  697. If you would like to use thread-locals in this context, use a `McpTransportContextProvider` bean.
  698. It can extract thread-locals and make them available in an `McpTransportContext` object.
  699. For HttpClient-based request customizers, the `McpTransportContext` will be available in the `customize` method. See,
  700. for example, with a Sync client (async works similarly):
  701. ```java
  702. @Configuration
  703. class McpConfiguration {
  704. @Bean
  705. McpSyncClientCustomizer syncClientCustomizer() {
  706. return (name, syncSpec) -> syncSpec.transportContextProvider(() -> {
  707. var myThing = MyThreadLocalThing.get();
  708. return McpTransportContext.create(Map.of("custom-key", myThing));
  709. });
  710. }
  711. @Bean
  712. McpSyncHttpClientRequestCustomizer requestCustomizer() {
  713. return (builder, method, endpoint, body, context) ->
  714. builder.header("x-custom-header", context.get("custom-key"));
  715. }
  716. }
  717. ```
  718. For WebClient-based filter functions, the `McpTransportContext` will be available in the Reactor context, under
  719. `McpTransportContext.KEY`:
  720. ```java
  721. @Configuration
  722. class McpConfiguration {
  723. @Bean
  724. McpSyncClientCustomizer syncClientCustomizer() {
  725. return (name, syncSpec) -> syncSpec.transportContextProvider(() -> {
  726. var myThing = MyThreadLocalThing.get();
  727. return McpTransportContext.create(Map.of("custom-key", myThing));
  728. });
  729. }
  730. @Bean
  731. WebClient.Builder mcpWebClientBuilder() {
  732. return WebClient.builder()
  733. .filter((request, next) ->
  734. Mono.deferContextual(reactorCtx -> {
  735. var transportCtx = reactorCtx.get(McpTransportContext.class);
  736. String customThing = transportCtx.get("custom-key").toString();
  737. var newRequest = ClientRequest.from(request)
  738. .header("x-custom-header", customThing)
  739. .build();
  740. return next.exchange(newRequest);
  741. })
  742. );
  743. }
  744. }
  745. ```
  746. ### Programmatically configure MCP clients
  747. If you'd like to bypass Spring AI's autoconfiguration altogether, you can create the MCP clients programmatically.
  748. The easiest way is to draw some inspiration on the transport
  749. auto-configurations ([HttpClient](https://github.com/spring-projects/spring-ai/blob/main/auto-configurations/mcp/spring-ai-autoconfigure-mcp-client-httpclient/src/main/java/org/springframework/ai/mcp/client/httpclient/autoconfigure/StreamableHttpHttpClientTransportAutoConfiguration.java), [WebClient](https://github.com/spring-projects/spring-ai/blob/main/auto-configurations/mcp/spring-ai-autoconfigure-mcp-client-webflux/src/main/java/org/springframework/ai/mcp/client/webflux/autoconfigure/StreamableHttpWebFluxTransportAutoConfiguration.java))
  750. as well as
  751. the [client auto-configuration](https://github.com/spring-projects/spring-ai/blob/main/auto-configurations/mcp/spring-ai-autoconfigure-mcp-client-common/src/main/java/org/springframework/ai/mcp/client/common/autoconfigure/McpClientAutoConfiguration.java).
  752. All in all, it could look like so:
  753. ```java
  754. // For HttpClient-based clients
  755. @Bean
  756. McpSyncClient client(
  757. ObjectMapper objectMapper,
  758. McpSyncHttpClientRequestCustomizer requestCustomizer,
  759. McpClientCommonProperties commonProps
  760. ) {
  761. var transport = HttpClientStreamableHttpTransport.builder(mcpServerUrl)
  762. .clientBuilder(HttpClient.newBuilder())
  763. .jsonMapper(new JacksonMcpJsonMapper(objectMapper))
  764. .httpRequestCustomizer(requestCustomizer)
  765. .build();
  766. var clientInfo = new McpSchema.Implementation("client-name", commonProps.getVersion());
  767. return McpClient.sync(transport)
  768. .clientInfo(clientInfo)
  769. .requestTimeout(commonProps.getRequestTimeout())
  770. .transportContextProvider(new AuthenticationMcpTransportContextProvider())
  771. .build();
  772. }
  773. //
  774. // -------------------------
  775. //
  776. // For WebClient based clients
  777. @Bean
  778. McpSyncClient client(
  779. WebClient.Builder mcpWebClientBuilder,
  780. ObjectMapper objectMapper,
  781. McpClientCommonProperties commonProperties
  782. ) {
  783. var builder = mcpWebClientBuilder.baseUrl(mcpServerUrl);
  784. var transport = WebClientStreamableHttpTransport.builder(builder)
  785. .jsonMapper(new JacksonMcpJsonMapper(objectMapper))
  786. .build();
  787. var clientInfo = new McpSchema.Implementation("clientName", commonProperties.getVersion());
  788. return McpClient.sync(transport)
  789. .clientInfo(clientInfo)
  790. .requestTimeout(commonProperties.getRequestTimeout())
  791. .transportContextProvider(new AuthenticationMcpTransportContextProvider())
  792. .build();
  793. }
  794. ```
  795. You can then add it to the tools available to a chat client:
  796. ```java
  797. var chatResponse = chatClient.prompt("Prompt the LLM to _do the thing_")
  798. .toolCallbacks(new SyncMcpToolCallbackProvider(mcpClient1, mcpClient2, mcpClient3))
  799. .call()
  800. .content();
  801. ```
  802. ### Known limitations
  803. - Spring WebFlux servers are not supported.
  804. - Spring AI autoconfiguration initializes the MCP client on app start.
  805. Most MCP servers want calls to be authenticated with a token, so you
  806. need to turn initialization off with `spring.ai.mcp.client.initialized=false`.
  807. Note:
  808. - Unlike the `mcp-server-security` module, the client implementation supports the SSE transport, both with `HttpClient`
  809. and `WebClient`.
  810. ## Authorization Server
  811. Enhances Spring
  812. Security's [OAuth 2.0 Authorization Server support](https://docs.spring.io/spring-security/reference/7.0/servlet/oauth2/authorization-server/index.html)
  813. with the RFCs and features relevant to the MCP authorization spec, such as Dynamic Client Registration and Resource
  814. Indicators.
  815. ### Quick start with `mcp-authorization-server-spring-boot` (recommended)
  816. The easiest way to set up an MCP authorization server is with the Boot auto-configuration module.
  817. It provides default `SecurityFilterChain`s that secure all endpoints and configure an MCP authorization server, with no additional configuration required.
  818. *Maven*
  819. ```xml
  820. <dependency>
  821. <groupId>org.springaicommunity</groupId>
  822. <artifactId>mcp-authorization-server-spring-boot</artifactId>
  823. <version>0.1.14</version>
  824. </dependency>
  825. ```
  826. *Gradle*
  827. ```groovy
  828. implementation("org.springaicommunity:mcp-authorization-server-spring-boot:0.1.14")
  829. ```
  830. ### Manual setup with `mcp-authorization-server`
  831. If you prefer wiring beans yourself (e.g. for advanced customization or non-Boot use-cases), you can use the lower-level `mcp-authorization-server` module directly.
  832. *Maven*
  833. ```xml
  834. <dependency>
  835. <groupId>org.springaicommunity</groupId>
  836. <artifactId>mcp-authorization-server</artifactId>
  837. <version>0.1.14</version>
  838. </dependency>
  839. ```
  840. *Gradle*
  841. ```groovy
  842. implementation("org.springaicommunity:mcp-authorization-server:0.1.14")
  843. ```
  844. ### Usage
  845. Configure the authorization server properties (see [reference documentation](https://docs.spring.io/spring-security/reference/7.0/servlet/oauth2/authorization-server/getting-started.html#oauth2AuthorizationServer-developing-your-first-application)).
  846. Here is an example `application.yml` for registering a default client:
  847. ```yaml
  848. spring:
  849. application:
  850. name: sample-authorization-server
  851. security:
  852. oauth2:
  853. authorizationserver:
  854. client:
  855. default-client:
  856. token:
  857. access-token-time-to-live: 1h
  858. registration:
  859. client-id: "default-client"
  860. client-secret: "{noop}default-secret"
  861. client-authentication-methods:
  862. - "client_secret_basic"
  863. - "none"
  864. authorization-grant-types:
  865. - "authorization_code"
  866. - "client_credentials"
  867. redirect-uris:
  868. - "http://127.0.0.1:8080/authorize/oauth2/code/authserver"
  869. - "http://localhost:8080/authorize/oauth2/code/authserver"
  870. # mcp-inspector
  871. - "http://localhost:6274/oauth/callback"
  872. # claude code
  873. - "https://claude.ai/api/mcp/auth_callback"
  874. user:
  875. # A single user, named "user"
  876. name: user
  877. password: password
  878. server:
  879. servlet:
  880. session:
  881. cookie:
  882. # Override the default cookie name (JSESSIONID).
  883. # This allows running multiple Spring apps on localhost, and they'll each have their own cookie.
  884. # Otherwise, since the cookies do not take the port into account, they are confused.
  885. name: MCP_AUTHORIZATION_SERVER_SESSIONID
  886. ```
  887. When using the manual setup, you must configure the authorization server properties as shown above, and then activate the authorization server capabilities with the usual Spring Security APIs in your security filter chain:
  888. ```java
  889. @Bean
  890. SecurityFilterChain securityFilterChain(HttpSecurity http) {
  891. return http
  892. // all requests must be authenticated
  893. .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
  894. // enable authorization server customizations
  895. .with(McpAuthorizationServerConfigurer.mcpAuthorizationServer(), withDefaults())
  896. // enable form-based login, for user "user"/"password"
  897. .formLogin(withDefaults())
  898. .build();
  899. }
  900. ```
  901. ### Dynamic Client Registration (DCR)
  902. By default, the authorization server supports Dynamic Client Registration (DCR).
  903. If you are using the Boot auto-configuration (`mcp-authorization-server-spring-boot`), you can disable it with the following property:
  904. ```properties
  905. spring.ai.mcp.authorizationserver.dynamic-client-registration.enabled=false
  906. ```
  907. If you are configuring the server manually, you can disable it via the configurer:
  908. ```java
  909. @Bean
  910. SecurityFilterChain securityFilterChain(HttpSecurity http) {
  911. return http
  912. .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
  913. .with(McpAuthorizationServerConfigurer.mcpAuthorizationServer(), mcp -> {
  914. mcp.dynamicClientRegistration(false);
  915. })
  916. .build();
  917. }
  918. ```
  919. ### Client ID Metadata Document (CIMD)
  920. CIMD is an alternative to DCR where the client identifies itself with a URL pointing to a metadata document
  921. it hosts. The authorization server fetches that document to validate the client, instead of relying on a
  922. prior registration.
  923. To enable it, use the `cimd(true)` option in `McpAuthorizationServerConfigurer` (disabled by default):
  924. ```java
  925. @Bean
  926. SecurityFilterChain securityFilterChain(HttpSecurity http) {
  927. return http
  928. .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
  929. .with(McpAuthorizationServerConfigurer.mcpAuthorizationServer(), mcp -> {
  930. mcp.cimd(true);
  931. })
  932. .formLogin(withDefaults())
  933. .build();
  934. }
  935. ```
  936. When CIMD is enabled, the authorization server:
  937. - Advertises `client_id_metadata_document` in its authorization server metadata
  938. - Accepts client_id URLs and fetches the corresponding metadata document to look up the client
  939. You also need to declare a `ClientIdMetadataDocumentRegisteredClientRepository` bean, which is responsible
  940. for fetching and validating the remote metadata document. If you also want to support traditionally registered
  941. clients (pre-registered or DCR) alongside CIMD, wrap both in a `DelegatingRegisteredClientRepository`.
  942. ```java
  943. @Bean
  944. ClientIdMetadataDocumentRegisteredClientRepository cimdClientRepository() {
  945. var repository = new ClientIdMetadataDocumentRegisteredClientRepository();
  946. repository.setMetadataDocumentResolver(new DefaultClientIdMetadataDocumentResolver());
  947. // Set allowLoopback=true in development to accept http://localhost URLs
  948. repository.setMetadataValidator(new DefaultClientMetadataValidator(new DefaultUrlValidator(false)));
  949. repository.setClientIdUrlValidator(new ClientIdUrlValidator(false));
  950. return repository;
  951. }
  952. ```
  953. The authorization server validates the redirect URI in an authorization request against
  954. the redirect URIs from the client metadata document. Some clients, such as Claude Code, use a dynamic port with
  955. the `localhost` host. To support those clients, configure `LocalhostWildcardPortValidator`
  956. alongside Spring Authorization Server's default scope validator:
  957. ```java
  958. @Bean
  959. SecurityFilterChain securityFilterChain(
  960. HttpSecurity http) {
  961. return http
  962. .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
  963. .with(McpAuthorizationServerConfigurer.mcpAuthorizationServer(), mcp -> {
  964. mcp.cimd(true);
  965. mcp.authorizationCodeRequestValidator(
  966. new LocalhostWildcardPortValidator()
  967. .andThen(DEFAULT_SCOPE_VALIDATOR));
  968. })
  969. .formLogin(withDefaults())
  970. .build();
  971. }
  972. ```
  973. ### Known limitations
  974. - Spring WebFlux servers are not supported.
  975. - Every client supports ALL `resource` identifiers.
  976. ## Samples
  977. The `samples` directory contains samples for these libraries.
  978. A [README.md](https://github.com/spring-ai-community/mcp-security/tree/main/samples) contains instructions for running
  979. those samples.
  980. A special directory is `samples/integration-tests`, which contains integration tests for all the submodules in this
  981. project.
  982. ## Integrations
  983. This is a work-in-progress, but with `mcp-server-security`, and a supporting `mcp-authorization-server`, you should be
  984. able to integrate with Cursor, Claude Code, and the MCP inspector.
  985. Note: if you use the MCP Inspector you may need to turn off CSRF and CORS protection.
  986. ## License
  987. This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.
  988. ---
  989. **Note:** This is a community-driven project and is not officially endorsed by Spring AI or the MCP project.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.