Spring
Follow
Securing MCP Servers with Spring AI
The Model Context Protocol (MCP) is a rapidly evolving standard in the AI world. Spring AI has launched a new project, mcp-security, to address the security needs of Spring users. This project provides support for securing MCP servers with OAuth 2 and API keys. The latest version of the MCP specification is gaining wider ecosystem support.
MCP servers exposed over HTTP must be secured using OAuth 2 access tokens as per the MCP specification. Calls to an MCP server require an Authorization header with a Bearer token. The MCP server must explicitly advertise the authorization servers it trusts for token acquisition. Spring AI integrates seamlessly with OAuth 2 resource servers, allowing applications to leverage existing authorization servers like Okta or GitHub.
To secure an MCP server with OAuth 2, users need to add specific dependencies to their Spring AI applications. These dependencies enable OAuth 2 resource server functionality and MCP-specific security configurations. Application properties are then used to configure the MCP server name, protocol, and the authorization server URL. A sample tool demonstrates how to retrieve user information from the authenticated JWT token.
An example security configuration class, McpServerSecurityConfiguration, demonstrates how to enforce authentication for all requests and configure OAuth 2 for the MCP server. This setup allows MCP clients to dynamically discover and utilize authorization servers. Spring Authorization Server can also be built to be MCP-compatible, supporting OAuth 2 Dynamic Client Registration and Resource Indicators.
While OAuth 2 is the mandated security mechanism, the MCP specification also supports API key-based authentication for environments lacking OAuth 2 infrastructure. The mcp-security project facilitates API key security by allowing custom headers for authentication. This involves adding specific dependencies for Spring Security and configuring an API key repository. The MCP server then validates the provided API key, which is typically sent as an X-API-key header.
The mcp-security project aims to improve MCP security and offers documentation and samples for both server-side and client-side security. Contributions and feedback are encouraged to further enhance the protocol's security features. The project also provides support for client-side MCP security within Spring AI and Spring Security.