Sajith Rahim | Almanac | Blog
 
Dev

Securing Spring AI MCP Server

Sajith AR

In the MCP security model, your server plays two distinct OAuth2 roles:

  • Resource Server : Validates incoming access tokens on all requests

  • Authorization Server : Issues tokens to authenticated clients

This dual role allows your MCP server to manage its own authentication while protecting its resources.

Configuration

Dependencies

First, add the necessary Spring Security dependencies:

	
        
    
        
    
    
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-authorization-server</artifactId>
</dependency>

Security Configuration

Configure your security filter chain to handle both OAuth2 roles:

	
        
    
        
    
    
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
            .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
            .with(authorizationServer(), Customizer.withDefaults())
            .oauth2ResourceServer(resource -> resource.jwt(Customizer.withDefaults()))
            .csrf(CsrfConfigurer::disable)
            .cors(Customizer.withDefaults())
            .build();
    }
}

Client Configuration

Define client credentials in your application properties:

	
        
    
        
    
    
spring.security.oauth2.authorizationserver.client.oidc-client.registration.client-id=mcp-client
spring.security.oauth2.authorizationserver.client.oidc-client.registration.client-secret={noop}secret
spring.security.oauth2.authorizationserver.client.oidc-client.registration.client-authentication-methods=client_secret_basic
spring.security.oauth2.authorizationserver.client.oidc-client.registration.authorization-grant-types=client_credentials

Token Management

Obtaining Access Tokens

Clients can obtain tokens using the client credentials grant:

	
        
    
        
    
    
curl -XPOST http://localhost:8080/oauth2/token \
  --data grant_type=client_credentials \
  --user mcp-client:secret

Making Authenticated Requests

Use the returned access token in subsequent requests:

	
        
    
        
    
    
curl http://localhost:8080/sse \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Testing with MCP Inspector

The MCP inspector (v0.6.0+) supports Bearer token authentication.

Simply paste your access token into the Authentication > Bearer field to test your secure MCP connections.


CONNECT

 
Have something to share,
Let's Connect