Securing a Spring AI MCP Server with OAuth 2.0 and Per-Tool Scopes
Build an OAuth authorization server and turn a Spring AI MCP server into a resource server, test it in MCP Inspector, then restrict single tools by scope.
This article is published in English.
Sources: Spring AI Recipe: Securing an MCP Server with OAuth
An API key is the easy way to protect an MCP server, but it is also a blunt instrument. When stronger protection is needed, OAuth 2.0 is the natural next step, and Spring AI can use it both to secure the server and to apply fine-grained authorization to individual tools. OAuth has secured apps and APIs for more than ten years, and a few MCP-specific extras let it cover MCP servers as well. The setup needs two pieces: an authorization server that issues tokens, and an MCP server that accepts them.
Building the authorization server
The authorization server is the place where a user logs in and lets a client access a resource server in their name. In MCP terms, the MCP server is the resource server, and the client is whatever agent or AI-enabled application calls it.
Start with a new Spring Boot project from the Initializr, either at start.spring.io or inside an IDE, with three dependencies selected: Spring Web, Spring Security and OAuth2 Authorization Server. One more dependency has to be added to the build after the project exists.
implementation 'org.springaicommunity:mcp-authorization-server:0.1.14'
That Spring AI Community library brings MCP-specific features to the authorization server, notably dynamic client registration (DCR) and resource indicators.
Next comes a configuration class that defines the security filter chain.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth ->
auth.anyRequest().authenticated())
.formLogin(withDefaults())
.with(
McpAuthorizationServerConfigurer.mcpAuthorizationServer(),
withDefaults())
.build();
}
}
This class does four things. It switches on web security, requires authentication for requests to the authorization server, turns on Spring Security's form login along with its default login page, and activates the MCP-specific authorization server capabilities.
The remaining work is configuration properties. YAML in src/main/resources/application.yaml suits these better than a properties file.
spring:
application:
name: recipes-authorization-server
security:
oauth2:
authorizationserver:
client:
default-client:
token:
access-token-time-to-live: 1h
registration:
client-id: "myclient"
client-secret: "{noop}mysecret"
client-authentication-methods:
- "client_secret_basic"
authorization-grant-types:
- "authorization_code"
redirect-uris:
- "http://localhost:6274/oauth/callback"
- "http://127.0.0.1:6274/oauth/callback"
scopes:
- general-access
- meteorology
- administration
user:
name: craig
password: letmein
server:
port: 9999
Most of this file declares one OAuth client. A production system would keep client registrations somewhere like a database, but a client defined in configuration is enough for a demonstration. The demo client uses the ID myclient and the secret mysecret. The secret carries a {noop} prefix, which tells Spring Security it is stored as plain text. That is convenient here and inadvisable anywhere real.
The client authenticates to the authorization server with HTTP Basic and uses the authorization code grant to get an access token. MCP Inspector will be the test tool. It can run on localhost or 127.0.0.1, listens on port 6274, and handles callbacks at the /oauth/callback path, so redirect URIs are set up for both host names.
The client may ask for any of three scopes when requesting a token: general-access, meteorology and administration. The configuration also defines one demo user. As with the client, a real deployment would load users from a proper user store. Port 9999 is where it listens.
That completes this side of the setup. It can be started right away or left until the MCP server is ready.
Turning the MCP server into a resource server
For the MCP server, begin from the code of the earlier API-key version. The build needs three dependencies.
implementation 'org.springaicommunity:mcp-server-security:0.1.14'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
The first two should already be present from the API-key setup. The third adds Spring Security's OAuth 2.0 resource server support.
The resource server must also know where its authorization server lives. With that server running on localhost at port 9999, one property in application.properties does it.
spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:9999
Auto-configuration covers much of the work, but the MCP server's security is configured explicitly so that the MCP security support is told where to find the authorization server.
@Configuration
@EnableWebSecurity
class McpSecurityConfig {
@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())
.with(
McpServerOAuth2Configurer.mcpServerOAuth2(),
(mcpAuthorization) -> {
mcpAuthorization.authorizationServer(issuerUrl);
}
)
.build();
}
}
The authorization server's location comes from the property defined a moment ago, and the filter chain requires authentication for every request. That is everything needed to make the MCP server an OAuth-protected resource server.
Trying it in MCP Inspector
Run both the authorization server and the MCP server, then start MCP Inspector using the instructions in the MCP documentation. The steps in the Inspector go like this:
- Click Add Servers at the top left and create a server with the URL http://localhost:3000, then click Add. A server panel appears.
- Before connecting, supply the client credentials. Open the Settings link at the bottom right of the panel, scroll to the OAuth Settings section at the bottom, expand it, and enter myclient as the Client ID and mysecret as the Client Secret.
- Leave everything else alone for now, Scopes included, and close the settings panel.
- Connect with the slider button at the top right of the server panel. If all is well, the browser redirects to the authorization server's login page. Sign in as the demo user defined in the YAML.
- After sign-in the browser returns to MCP Inspector with a successful connection, and the requests that set it up appear in the panel on the right.
- Open the Tools tab. The list should include get-weather-for-zipcode. Select it, type any ZIP code into the zipcode field and click Execute Tool. The result from the MCP server comes back as JSON.
The MCP server now demands OAuth authentication. But so far it is all or nothing: a client that is authorized to connect can use everything the server exposes.
Protecting individual tools
The security applied so far covers the server as a whole. Tools, resources, prompts and other capabilities all sit behind an authenticated connection, but once a client is through that front door everything is available. If different tools, prompts or resources carry different authorization requirements, Spring Security's method security allows finer rules.
The first change is to the MCP server's security configuration.
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
class SecurityConfig {
@Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
private String issuerUrl;
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> {
auth.requestMatchers("/mcp").permitAll();
auth.anyRequest().authenticated();
})
.with(
McpServerOAuth2Configurer.mcpServerOAuth2(),
(mcpAuthorization) -> {
mcpAuthorization.authorizationServer(issuerUrl);
}
)
.build();
}
}
Two things differ. The class now carries @EnableMethodSecurity, which makes it possible to put authorization rules directly on tool methods. And instead of requiring authentication on every request, authorizeHttpRequests() now lets requests to the /mcp endpoint through without conditions while still requiring authentication elsewhere. Authorization of each tool invocation is then enforced at the method level.
Suppose that calling get-weather-for-zipcode should demand the meteorology OAuth scope. The @PreAuthorize annotation expresses that.
@PreAuthorize("hasAuthority('SCOPE_meteorology')")
@McpTool(
name = "get-weather-for-zipcode",
description = "Gets the weather for a given zipcode",
annotations = @McpTool.McpAnnotations(
openWorldHint = false,
destructiveHint = false,
idempotentHint = true))
Weather getWeatherForZipcode(
@McpToolParam(description = "The zipcode to get weather for")
String zipcode) {
var context = SecurityContextHolder.getContext();
var username = context.getAuthentication().getName();
return new Weather(
zipcode,
"Raining cats and dogs",
78.0f,
username);
}
The annotation requires that the current authorization include the meteorology scope. Spring Security models OAuth scopes as granted authorities prefixed with SCOPE_, which explains why the expression checks for SCOPE_meteorology.
The tool definition also gains a few optional hint attributes, supplied through the annotations attribute, which give clients useful information:
- The tool is not open-world. It is fully self-contained and calls no external API. If it were rewritten to use a weather API, the hint should be true, or simply omitted, since it defaults to true.
- The tool changes and deletes nothing, because it only fetches weather data, so it is not destructive.
- Being non-destructive makes it idempotent. For a destructive tool, idempotency deserves thought and the idempotentHint attribute should be set to match.
Seeing the scope check work
Restart the MCP server, switch back to MCP Inspector, and open OAuth Settings before reconnecting. The Clear stored OAuth state button at the bottom throws away any tokens left over from the previous authorization, so use it.
Reconnect, sign in, go back to get-weather-for-zipcode and invoke it again. This time the call will most likely fail. The authorization server was never asked to grant the meteorology scope, so authentication alone no longer suffices for this tool.
Now add meteorology to the Scopes field in OAuth Settings, clear the stored state if necessary, reconnect and run the tool once more. It should succeed, because the freshly issued access token carries the meteorology scope that @PreAuthorize demands.
A handful of additions to Spring Security's existing OAuth support is all it took to move from an API-key-protected MCP server to one that requires OAuth, and then to scope-based authorization on individual tools.