iTranslated by AI
Implementing and Testing MCP Authorization with Claude
Introduction
The progress of generative AI these days is remarkable. One of the factors driving this progress is the MCP. In this article, I will explore the authorization features of MCP by reviewing the documentation and creating a practical implementation. While this might not be a perfect solution, I hope it helps you grasp the overview of MCP Authorization at an implementation level. It is a bit long, but I hope you will bear with me.
Grasping the Overview of MCP Documentation
First, I will read the Authorization documentation provided by MCP and record a brief overview and my thoughts. Note that the version I am reading was published on June 18, 2025.
1.1 Purpose and Scope
It seems to be based on HTTP communication. Other standards appear to describe the role of generic OAuth.
1.2 Protocol Requirements
This section describes points to note when building an authorization flow in MCP. It mentions the following three patterns:
- For HTTP communication, adhere to this document.
- For STDIO communication, do not adhere to this document.
- For other communication methods, follow the best practices for that communication.
MCP Authorization seems to focus primarily on HTTP communication.
1.3 Standards Compliance
This section outlines the RFCs to comply with when implementing authorization features. Specifically:
- OAuth 2.1 IETF DRAFT (draft-ietf-oauth-v2-1-12)
- OAuth 2.0 Authorization Server Metadata (RFC8414)
- OAuth 2.0 Dynamic Client Registration Protocol (RFC7591)
- OAuth 2.0 Protected Resource Metadata (RFC9728)
However, the Dynamic Client Registration Protocol seems optional. Unless you are publishing the MCP server, there is likely little motivation to implement dynamic clients. For the others, I believe they should generally be implemented. While you could potentially skip the Metadata implementations if you have special circumstances (like a very tight deadline), it would sacrifice interoperability, so I feel they should basically be implemented.
2. Authorization Flow
This is an explanation based on the OAuth 2.0 Authorization Code flow. The following flow found in the documentation covers everything.

Regarding the above, since it includes dynamic client registration and details of the Authorization Code flow, I think the "2.3.3 Sequence Diagram" is better for grasping the big picture.

The flow above can be broadly summarized into two parts:
- Obtaining the Authorization Server's Metadata
- Performing the Authorization Code flow based on the values in the above Metadata
For details, it is best to refer to the RFCs involved in each flow, as they are essentially complied with. Note that in this section, in addition to the RFCs mentioned in 1.3 Standards Compliance, the implementation of the resource parameter (RFC 8707) is made mandatory. Even if the authorization server does not implement the resource parameter feature, it seems that configuration is always required.
I could not find the specific reason why the resource parameter is necessary, but if a request is made with the audience included in the default returned token, there is a possibility that servers not intended by the MCP client could also be executed. Therefore, I felt it is natural to specify the resource parameter and create a token targeted only at the MCP server corresponding to the MCP client.
3. Security Considerations
Security considerations regarding authorization features were documented here. While various things are written, I think it is better to read through the OAuth 2.1 specification that forms the basis of the content. Since that document contains points to note beyond this one, I thought it was more appropriate to point you toward OAuth 2.1 than to try to summarize it here (this is definitely not because I found it troublesome).
Notable Changes from the Previous Version
The documentation was updated on June 18, 2025. Since the previous version was from March 26, 2025, I will briefly touch upon the differences that caught my attention.
It is that the MCP server is now defined as a resource server within the context of OAuth 2.1. In the previous version, MCP servers were not necessarily limited to being resource servers, and the wording allowed the MCP server itself to act as an authorization server. However, it is no longer expected for an MCP server to act as an authorization server. Consequently, OAuth 2.0 Protected Resource Metadata (RFC9728), which was not previously mentioned, has been added.
Personally, I feel this change is quite impressive. By separating the role of the authorization server and defining the ideal form of an MCP server, I believe it has reduced the burden of implementing an MCP server. Having to provide authorization server functionality would involve too much to think about and would be exhausting. As described above, I think the point of clearly defining the MCP server as a resource server is the difference from the previous version.
So far, I have briefly touched upon the contents of the documentation. From here on, I will actually build a simple MCP client and server to run the Authorization Code flow. Note that I will not cover the overview of MCP or the details of implementing MCP clients and servers. I will focus solely on explaining the Authorization Code flow.
Building the Authorization Code Flow
Here, I am actually building the OAuth 2.0 Authorization Code flow along with MCP. By the way, the MCP server I created is a simple tool that returns the results of arithmetic operations.
Sequence Diagram
The sequence of the feature is as follows:
The flow itself does not deviate much from the MCP documentation, but you might find the existence of the "MCP Client" confusing. While both Claude and an MCP Client exist, some of you might be wondering, "Isn't Claude acting as the MCP client?" That is a fair point. Ideally, preparing a separate MCP client should be unnecessary. However, when I tried to use Claude as the MCP client this time, I could not perform the steps from metadata fetching to building the Authorization Code flow. Therefore, I built an MCP client as a proxy to perform the Authorization Code flow with the MCP server.
If you know of any other methods or ways to execute the Authorization Code flow within Claude itself, please let me know.
Also, regarding the authorization server, I am using Auth0. Any server with authorization server functionality would work, but I chose Auth0 because it was easy to set up with minimal effort.
Preparation Before Implementation
Before we look at the implementation and verify the operation, the following prerequisites must be met:
- You can use Node.js.
- A "Regular Web Application" exists in your Auth0 dashboard under Applications → Applications (the name can be anything).
- Please include the Client ID and Client Secret of the created app in the
.envfile of the repository to be shared later. 
- Please include the Client ID and Client Secret of the created app in the
- An API has been created in the Auth0 dashboard under Applications → APIs where the resource server URL is set as the Audience (the name can also be anything).
- The app and API created in the two steps above have been associated with each other.
- An arbitrary user has been created in the Auth0 dashboard under User Management → Users.
This completes the preparations. Auth0 really makes it easy. Now, let's look at the implementation.
Note that, in theory, we should properly implement OAuth 2.0 Authorization Server Metadata (RFC8414) and OAuth 2.0 Protected Resource Metadata (RFC9728). However, since priority was given to getting it working, the Metadata part is not fully implemented. Also, I will barely touch upon the processing required to run as an MCP client or MCP server. This is because, as an amateur, writing about it might lead to including errors. Since there is already plenty of useful information available regarding MCP communication (including in Japanese), please refer to those sources separately. If you find errors in my implementation based on that information, I would appreciate it if you could point them out. Thank you for your understanding.
Implementation Details
First, here is the repository:
Since the entire implementation is in the repository above, I will provide a brief explanation of the key parts here. Let's start with the MCP client.
In the MCP client, the main file is mcp-client.ts, and the handleMCPRequest method is the core of this implementation. While you can check the full picture in the GitHub code, here I will break down the processing content.
First, the initial processing:
/** Fetch access token: from parameters or memory cache */
const cachedAccessToken = memoryStorage.getAccessToken();
/** Send HTTP request to MCP server (authenticate with Bearer token if an access token exists) */
const response = await this.httpClient.makeRequest(
request.method,
request.params,
cachedAccessToken
? { Authorization: `Bearer ${cachedAccessToken}` }
: undefined
);
The access token obtained is stored in memory. Therefore, if an access token already exists, it is used to request the MCP server.
Next, the processing to initiate the Authorization Code flow:
/** Get the WWW-Authenticate header from the OAuth2 resource server */
const wwwAuthenticateHeader = response.headers.get('www-authenticate');
/** If the status is 401 Unauthorized and the WWW-Authenticate header exists, start the OAuth2 authorization flow */
if (!response.ok && response.status === 401 && wwwAuthenticateHeader) {
/** Omitted */
}
I check if the response from the MCP server includes a WWW-Authenticate header and if the error is a 401. If the response status is 401 and the header exists, it serves as a signal to start the Authorization Code flow. Therefore, when the conditions are met, the processing required for the flow is executed internally.
Let's look at the inside. First, the processing to obtain the authorization server information:
/** Extract the resource metadata URL from the WWW-Authenticate header using regex */
const resourceMetadata = wwwAuthenticateHeader.match(/Bearer\s+resource_metadata="([^"]+)"/);
if (resourceMetadata) {
const resourceMetadataUrl = resourceMetadata[1];
/** Fetch JSON from the resource metadata URL */
const metadataResponse = await fetch(resourceMetadataUrl);
if (!metadataResponse.ok) {
throw new Error(`Failed to fetch resource metadata: ${metadataResponse.statusText}`);
}
const metadataJson: any = await metadataResponse.json();
/**
* Get authorization server URL from resource metadata
* In theory, there could be multiple authorization servers, requiring logic to choose one,
* but here we use the first one.
*/
const authorizationServerUrl = metadataJson.authorization_servers[0];
if (!authorizationServerUrl) {
throw new Error('No authorization servers found in resource metadata');
}
/** Fetch authorization server configuration */
const authServerConfigUrl = `${authorizationServerUrl}/.well-known/oauth-authorization-server`;
const authServerConfigResponse = await fetch(authServerConfigUrl);
if (!authServerConfigResponse.ok) {
throw new Error(`Failed to fetch auth server config: ${authServerConfigResponse.statusText}`);
}
const authServerConfig: any = await authServerConfigResponse.json();
/** Get authorization endpoint URL from authorization server config */
const authUrl = new URL(authServerConfig.authorization_endpoint);
/** ...omitted */
}
First, I fetch the metadata from the resource server. The authorization_servers property contains the URL of the authorization server. Using this URL, I request the metadata information from the authorization server to obtain the URLs necessary for the Authorization Code flow.
Once the URL is obtained, I add the necessary parameters to access the various endpoints.
/** Step 2: Prepare parameters for the Authorization Code flow */
const clientId = process.env.CLIENT_ID || "";
/** Specify the URL of the MCP client prepared to handle the authorization code as the redirect URI */
const redirectUri = "http://localhost:8000/verify";
const scope = "openid profile";
const state = Math.random().toString(36).substring(2, 15);
/** Save the state parameter to memory */
memoryStorage.storeState(state);
/** Generate and store PKCE (Proof Key for Code Exchange) parameters */
const { codeChallenge } = memoryStorage.generateAndStorePKCE();
/** Step 3: Construct the authorization URL */
authUrl.searchParams.set("response_type", "code");
authUrl.searchParams.set("client_id", clientId);
authUrl.searchParams.set("redirect_uri", redirectUri);
authUrl.searchParams.set("scope", scope);
authUrl.searchParams.set("state", state);
authUrl.searchParams.set("resource", "http://localhost:3000");
/**
* Set the audience parameter according to Auth0's specifications.
* Without this, the payload of the access token returned from Auth0 will be empty.
* While this is not a standard specification, it must be set.
*/
authUrl.searchParams.set("audience", "http://localhost:3000");
/** Add PKCE parameters */
authUrl.searchParams.set("code_challenge", codeChallenge);
authUrl.searchParams.set("code_challenge_method", "S256");
/** Step 4: Open the authorization screen in the browser */
await this.openBrowserAndConfirm(authUrl.toString());
For the various parameters, please refer to OAuth2.1. Once the URL is created by adding the parameters, I open a separate browser to access the authorization server and perform authentication.※
Once logging in via Auth0 is completed, it redirects to the screen set in simple-http-server.ts, where the access token is obtained and saved from the authorization code. If successful, the screen is displayed. The flow for obtaining the access token is outside the scope of this MCP documentation and is purely an OAuth2 matter, so details are omitted.
The following processing runs while opening the browser until the token is obtained:
/** Step 5: Wait until the access token is obtained */
const waitForToken = (): Promise<string> => {
return new Promise((resolve, reject) => {
const checkToken = () => {
const token = memoryStorage.getAccessToken();
if (token) {
resolve(token);
return;
}
setTimeout(checkToken, 500);
};
checkToken();
// Timeout after 30 seconds
setTimeout(() => {
reject(new Error("Timeout waiting for access token"));
}, 30000);
});
};
await waitForToken();
If the subsequent processing proceeds while opening the browser and performing login, no access token will have been obtained, causing the browser to open indefinitely. Therefore, I wait until the browser is opened and the access token is saved. This ensures that the subsequent processing is executed only after the access token is successfully obtained on the screen.
The subsequent processing executes the same handleMCPRequest method. Now, since an access token exists, if the token is valid, no 401 error will be returned when requesting the MCP server.
This concludes the main implementation parts for the MCP client.
I will also look at the MCP server. Although, regarding the MCP server, it is probably just the part that returns the 401 error and the metadata endpoint. Other parts, such as token validation or processes for handling MCP communication, are omitted as they are not the focus of this article.
Comments are included in each process, so please check mcp-server.ts if you are interested.
The implementation for returning a 401 error is as follows:
app.post("/mcp", async (req: Request, res: Response) => {
/** JSON-RPC request body from the client */
const request = req.body;
/** HTTP headers of the request (including Authorization header, etc.) */
const headers = req.headers;
/**
* Handling for the tool execution method (OAuth2 authentication required)
*
* Method used when Claude actually calls a tool.
* This method requires access token validation,
* and returns a 401 Unauthorized error if authentication fails.
*/
if (request.method === "tools/call") {
/** Obtain Authorization header from HTTP request */
const authHeader = headers['authorization'];
/** 401 error if there is no Authorization header or if it is not a Bearer scheme */
if (!authHeader || !authHeader.startsWith('Bearer ')) {
/**
* 401 response compliant with RFC 6750 (OAuth 2.0 Bearer Token Usage)
* Notify the resource metadata URL via the WWW-Authenticate header
*/
res.status(401).header({
"WWW-Authenticate": 'Bearer resource_metadata="http://localhost:3000/.well-known/oauth-protected-resource"'
}).json({
jsonrpc: "2.0",
id: request.id,
error: { code: -32000, message: "Unauthorized" }
});
return;
}
/** Extract access token by removing the "Bearer " prefix from the Authorization header */
const token = authHeader.replace(/Bearer\s+/, '');
/** Execute Auth0 JWT access token validation */
try {
const isValid = await validateToken(token);
console.log('Token is valid:', isValid);
/** If token validation fails, return a 401 error to prompt re-authentication */
if (!isValid) {
res.status(401).header({
"WWW-Authenticate": 'Bearer resource_metadata="http://localhost:3000/.well-known/oauth-protected-resource"'
}).json({
jsonrpc: "2.0",
id: request.id,
error: { code: -32000, message: "Invalid token" }
});
return;
}
} catch (error) {
/** Catch exceptions during token validation and return a 401 error */
console.error('Token validation error:', error);
res.status(401).header({
"WWW-Authenticate": 'Bearer resource_metadata="http://localhost:3000/.well-known/oauth-protected-resource"'
}).json({
jsonrpc: "2.0",
id: request.id,
error: { code: -32000, message: "Token validation failed" }
});
return;
}
/** Omitted */
});
I obtain the Bearer token from the Authorization header, and if it is missing, I return a 401 with the URL to fetch the resource server metadata in the WWW-Authenticate header. Also, even if it exists, if the token is not valid, I set the same response to prompt the acquisition of an access token again.
The implementation for the Metadata endpoint is as follows:
app.get('/.well-known/oauth-protected-resource', (req: Request, res: Response) => {
res.json(
{
/** The URI of this resource server */
"resource":
"http://localhost:3000",
/** List of authorization servers protecting this resource */
"authorization_servers":
["https://mcp-authorization-server.jp.auth0.com"],
}
);
});
There are technically other properties, but I have kept it to the bare minimum this time. This concludes the implementation section. Now, let's proceed to the verification.
Verification
To perform the verification, I carried out the following steps:
- Built the project (executed
npm run build) - Started the MCP server
- Added connection information to the Claude Desktop configuration settings
First, starting the MCP server. Ideally, the MCP server should be deployed separately, but I ran it locally this time for simplicity. You can start it by running npm run server. Note that the MCP client in the repository I provided assumes the MCP server is running locally, so if you want to access a remote one, you will need to modify the code accordingly.
Once it's running, I entered the connection information into the Claude Desktop configuration file. You can use any method to open the configuration file, but I usually open it from the hamburger menu in the top left of Claude Desktop by selecting "Developer" -> "Open App Config".

Once the JSON file is open, I added the configuration inside the mcpServers property so that it executes the npm run client script. I set it up as follows:
"sample-calculator": {
"command": "wsl",
"args": [
"-d",
"Ubuntu",
"-e",
"bash",
"-c",
"cd [path to project] && npm run client"
]
}
My setup is somewhat unique as I am running the project on WSL and have Claude Desktop installed on Windows. Please adjust the sample-calculator property to suit your environment. Essentially, as long as it executes npm run client or the node command pointing to dist/client/index.js, it should work.
After saving the configuration, I restarted Claude. You must restart it for the settings to take effect—simply closing the window is not enough; you should fully exit the application (e.g., via "File" -> "Exit").
Once restarted, the MCP client I created should be available. You can verify this by clicking on "Search and Tools" and checking if sample-calculator appears.

At this point, you might see an error in Claude like this:

Ideally, this should be fixed, but I didn't know the immediate fix and it works despite this, so I ignored it. Please forgive these occasional imperfections.
Once everything is ready, here is a demo of the flow in action. I used the prompt: "Use sample-calculator to calculate 1+2+3."

You can see it attempting to access the MCP client, triggering the Auth0 login screen, and returning the calculation result only after logging in. (Please ignore the "Invalid JSON" error that appears).
This concludes the verification.
Thoughts After Implementation
Finally, here are my thoughts after going through this implementation.
I want to use Claude as the MCP client
This was my primary takeaway. I had to set up an MCP client as a proxy, but I would rather avoid implementing that if possible. In this implementation, I used OpenID Connect, but I didn't verify the received ID token. Leaving security up to individual implementations invites lapses and omissions. Furthermore, controlling browser launches and waiting for the access token to be retrieved was quite cumbersome, and doing it properly is even more challenging. It would be great if Claude could handle those features.
Access token storage
Deciding how to store the access token was a significant struggle. Since this MCP client won't likely be deployed, it has to work locally. Without a database, I considered using the system Keychain to encrypt and store the token in a file. However, that proved to be very incompatible with Node.js. While there is a module called keytar, it is now archived. I suspect that implementing it in Electron would be necessary to bridge Keychain support with OAuth redirects. Building a mechanism that persists tokens and avoids repeated server access while tokens are valid presented significant hurdles. Therefore, I stored the token in-memory, so it lasts as long as Claude Desktop is running. You won't need to re-authenticate until you shut down your PC or exit Claude. While you have to authenticate once a day, I accepted this trade-off for now. It really highlights the difficulty of balancing UX and security.
Conclusion
I have recreated the MCP Authorization documentation using an MCP client, server, and an authorization server. Despite some imperfections, I am relieved to have completed the full flow. Implementing this and clearly separating the authorization server helped define the boundaries of what MCP clients and servers need to do. There are still many considerations and gaps, so I hope to iterate and refine this further. Thank you for reading.


Discussion