ThisCalculator

Everyday

Add Authentication & Authorization to an MCP Server

Updated · Standard formula, shown below

This guide shows you how to add authentication and authorization to a Model Context Protocol (MCP) server. You’ll learn to protect your server’s tools and resources so only verified clients can call them, and each client only sees what they’re allowed to. We’ll cover both the OAuth 2.1 flow (for remote servers) and a simpler API-key approach (for local or internal use).

What You’ll Need

  • An MCP server already implemented (in TypeScript, Python, or another supported language).
  • An MCP client that supports the auth flow (e.g., the official MCP Inspector, Claude Desktop with remote servers, or a custom client using the MCP SDK).
  • For OAuth: a way to issue tokens (e.g., an existing identity provider like Auth0, or a simple in-house token service).
  • For API keys: a secure storage for keys (e.g., environment variables or a secrets manager).
  • Basic knowledge of HTTP and JSON.

Step-by-Step

  1. Choose your auth method. If your server is only accessible on localhost or a trusted network, an API key sent in the Authorization header is simplest. For public or multi-tenant servers, implement OAuth 2.1 (or 2.0) with the MCP-specific discovery flow.
  2. Add the authorization metadata to your server. In your MCP server definition, add an authorization field that advertises the supported methods. For OAuth, include the authorization_url and token_url. For API keys, you can just document the header name.
  3. Implement the token validation middleware. Before any MCP request is handled, validate the incoming token. For API keys, compare against your stored keys. For OAuth, verify the JWT signature and expiry using your identity provider’s public keys.
  4. Protect each tool or resource individually. After validating the token, check whether the authenticated principal (user or service) has permission to access the specific tool or resource being requested. Store permissions in a simple role-based or ACL system.
  5. Return proper errors. If the token is missing or invalid, return an HTTP 401 with an error message. If the token is valid but the user lacks permission, return 403. The MCP client will display these errors to the end user.
  6. Test with the MCP Inspector. Launch the Inspector with your server URL. It will prompt you to log in (if OAuth) or let you add a custom header (for API keys). Verify that unauthenticated requests are rejected and that authorized requests work.
  7. Add refresh token handling (OAuth only). If your tokens expire, implement a refresh flow so clients can get new access tokens without re-authenticating. Store refresh tokens securely and rotate them.

Common Mistakes

  • Storing tokens in plain text. Always hash API keys and encrypt tokens at rest.
  • Not validating token audience. Ensure the token’s aud claim matches your server’s identifier to prevent token reuse across services.
  • Ignoring CORS. If your server is accessed from a browser-based client, you must configure CORS to allow the Authorization header.
  • Hardcoding secrets in source code. Use environment variables or a secrets manager.
  • Forgetting to check permissions on every tool. A single unguarded tool can expose sensitive data.

Tips

  • Use standard OAuth libraries (like oauth2 in Python or passport in Node.js) to avoid security pitfalls.
  • For API keys, allow multiple keys per user so they can be rotated without downtime.
  • Log all auth failures (without logging the tokens themselves) to detect brute-force attempts.
  • When using OAuth, consider using the PKCE flow for public clients (like desktop apps) to prevent authorization code interception.
  • Keep your token expiry short (e.g., 15 minutes) and use refresh tokens for longer sessions.

Troubleshooting

Client gets 401 even with a valid token. Check that the token is being sent in the correct header (Authorization: Bearer <token>). Also verify the server’s clock is synchronized (JWT validation depends on time).

OAuth discovery fails. Ensure your server exposes the .well-known/oauth-authorization-server endpoint (or the MCP-specific /.well-known/mcp/ endpoint) with the correct URLs. Test with curl.

Permissions not applied. Make sure you’re checking permissions after authentication, not before. Also verify that the permission check is called for every tool, not just in the main handler.

Refresh token not working. Check that the refresh token is stored securely and that the token endpoint accepts it. Some identity providers require the client to send the client_id even for public clients.

Inspector doesn’t prompt for login. The Inspector only shows the auth dialog if the server advertises the authorization metadata. Double-check your server’s initialization response.

Frequently Asked Questions

  1. Can I use an API key with a remote MCP server? Yes, but you should use HTTPS and consider the key as a shared secret. For public servers, OAuth is more secure and allows per-user revocation.
  2. Do I need to implement OAuth from scratch? No. Use an existing identity provider (like Auth0, Okta, or Keycloak) or a library that handles the OAuth flow. You only need to integrate it with your MCP server.
  3. What is the difference between authentication and authorization? Authentication verifies who you are (e.g., via a token). Authorization determines what you can do (e.g., which tools you can call). Both are needed for a secure server.
  4. Can I use JWT for API keys? Yes, but it’s overkill. A simple random string stored in a database is fine. If you use JWT, ensure you verify the signature and expiry.
  5. How do I revoke a user’s access? For API keys, delete the key from your database. For OAuth, implement token revocation (or rely on short expiry times).
  6. Does the MCP protocol support authentication natively? The MCP specification defines how to advertise and perform OAuth, but the actual token validation is up to your server implementation.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.