MCP Authentication and Authorization
🎯 Introduction
Our MCP server already provides product lookup tools. Before allowing other AI applications to use it, we need to restrict which clients can access the service and which tools they can use. Otherwise, unauthorized applications could query company stock, customer information, and other data.
This article adds access token validation to the existing server and tests access with and without a valid token. We then use an employee authorizing an AI application to check stock to explain MCP's OAuth authorization mechanism. The hands-on example uses a shared token only; we will not build an OAuth authorization server.
🧱 Why Authentication and Authorization?
Suppose customer support staff may check stock, but only warehouse administrators may change it.
- Authentication: verify a caller's identity or the validity of their credentials.
- Authorization: determine whether the caller is permitted to perform the requested operation.
Passing authentication does not grant access to every tool. For example, support staff may call get_stock but may not change stock quantities.
For an HTTP MCP server, we can validate access tokens as requests enter /mcp, then check permissions for individual tools according to business requirements.
🧱 Add Access Control to the MCP Service
Continue using 02.first-server.mjs and 02.first-client.mjs in mcp-demo, with business-api.mjs running. No new service or dependencies are needed.
1. Validate the Access Token
Create .env.mcp in the project root and configure a randomly generated access token:
MCP_TOKEN=replace_with_your_own_random_token
Generate a random value with this command, then copy it into the configuration file (do not share the generated token):
node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))"
Add .env.mcp to .gitignore. This token controls access between the client and MCP server; it is unrelated to the model API key.
At the top of 02.first-server.mjs, add the import and read the token:
import { timingSafeEqual } from "node:crypto";
const token = process.env.MCP_TOKEN;
if (!token || !/^[a-f0-9]{64}$/.test(token)) {
throw new Error("Configure a valid MCP_TOKEN");
}
The rule is simple: the client includes a token in the Authorization header, and the server compares it with the configured token. A match allows the request to continue; otherwise, the server returns 401.
Add authentication middleware before the existing app.all() route:
function checkToken(req, res, next) {
const actual = Buffer.from(req.get("Authorization") ?? "");
const expected = Buffer.from(`Bearer ${token}`);
if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
res.set("WWW-Authenticate", "Bearer");
return res.status(401).json({ message: "Invalid credentials" });
}
next();
}
Buffer.from() converts the strings to bytes, and timingSafeEqual() compares them to reduce the risk of inferring credentials from comparison timing. This method requires equal-length inputs, so we check lengths first.
Replace the existing /mcp route with:
app.all("/mcp", checkToken, (req, res) => {
void nodeHandler(req, res, req.body);
});
All MCP requests to /mcp now pass token validation first, rather than checking only product tool calls.
Stop the existing server process and restart it:
node --env-file=.env.mcp 02.first-server.mjs
2. Test an Unauthenticated Request
Without changing the existing 02.first-client.mjs, run:
node 02.first-client.mjs
Because the client sends no token, the server returns HTTP 401 Unauthorized, preventing MCP initialization. The SDK may surface a connection exception or an authorization-required error; the exact message depends on the version.
The client cannot even retrieve the tool list, let alone execute a stock lookup.
3. Send the Token from the Client
In 02.first-client.mjs, replace the existing transport definition with:
const token = process.env.MCP_TOKEN;
if (!token) {
throw new Error("MCP_TOKEN is missing");
}
const transport = new StreamableHTTPClientTransport(
new URL("http://127.0.0.1:3200/mcp"),
{
requestInit: {
headers: { Authorization: `Bearer ${token}` }
}
}
);
requestInit.headers sets headers on the transport's HTTP requests. The client only needs to include credentials when communicating; tool arguments do not change.
Inside try, replace the calls and logging after connection with the existing stock lookup:
const result = await client.callTool({
name: "get_stock",
arguments: { id: "P100" }
});
console.log(JSON.stringify(result, null, 4));
Run it again:
node --env-file=.env.mcp 02.first-client.mjs
Key fields in the expected result:
{
"content": [
{
"type": "text",
"text": "Mechanical Keyboard has 12 units in stock"
}
]
}
This confirms that the client passed the entry-point check and called the product tool. To keep the previous article's AI application working with this server, make the same change to transport in 06.ai-chat.mjs and run it with node --env-file=.env --env-file=.env.mcp 06.ai-chat.mjs.
🧱 MCP OAuth Authorization
Why Is a Shared Token Insufficient?
In the experiment, every client uses the same token. Giving that token to every employee would not let the company distinguish employees or revoke one employee's access individually.
Suppose a support employee wants to check company stock in Cursor. A better approach is to let the employee sign in with their company account and authorize Cursor to read stock on a company authorization page, rather than giving Cursor their password or a shared token.
OAuth is an authorization mechanism that lets an application obtain a limited-permission access token to access a service on a user's behalf. MCP's HTTP authorization specification builds on this to define authorization server discovery, token acquisition, and access to protected MCP servers.
Roles in Authorization
| Role | Responsibility |
|---|---|
| MCP client (inside Cursor) | Request authorization, obtain tokens, and call tools |
| Authorization server (the company's identity service) | Handle employee sign-in, consent, and token issuance |
| MCP server (the product service) | Validate tokens and permissions, then execute product lookups |
In OAuth, a service providing protected data or functionality is called a resource server. Here, that is the product MCP server. This term is unrelated to MCP's Resources capability.
The MCP server can use an existing authorization server instead of implementing its own login system.
OAuth Authorization Flow
Suppose an employee configures https://mcp.example.com/mcp in a version of Cursor that supports MCP OAuth. The company has already deployed its authorization server at https://auth.example.com.
Step 1: Discover the Authorization Endpoint
When the employee connects, the client has no access token. The MCP server returns 401 and uses WWW-Authenticate to tell the client where to find authorization information:
WWW-Authenticate: Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource/mcp"
The client requests this URL and receives resource metadata describing the service and its authorization configuration:
{
"resource": "https://mcp.example.com/mcp",
"authorization_servers": ["https://auth.example.com"]
}
The client now knows which authorization server to use. It reads that server's published endpoint information to locate the authorization page and token endpoint. Users do not need to configure these endpoint URLs themselves.
Step 2: The Employee Signs In and Grants Consent
The client opens the authorization page in a browser. The employee signs in with their company account and allows Cursor to read product stock.
The authorization server returns a short-lived, single-use authorization code to the client through a browser redirect. The client exchanges the code for an access token. The code is not a credential for accessing the MCP server; it is only used to obtain a token. To prevent misuse of intercepted codes, the client generates a random verifier when starting authorization and proves possession of it during the exchange. This is the basic purpose of PKCE.
The company's identity service handles the employee's password throughout; it does not need to be given to Cursor.
Step 3: Use the Access Token to Check Stock
After obtaining a token, the client connects to the product MCP server again with this header:
Authorization: Bearer <access_token>
This is the same header used in the shared-token experiment. The difference is that the server must now validate a token issued by the authorization server instead of comparing a fixed string.
Suppose the company grants Cursor stock:read, meaning permission to read stock. When accepting requests, the server needs to check:
| Check | Why it matters |
|---|---|
| Issuer | Ensure the token comes from a trusted authorization server |
| Expiration | Prevent use of expired tokens |
| Audience | Prevent tokens intended for other services from accessing the product MCP server |
| Scope | Confirm the token grants the permission required for the operation, such as stock:read |
These claims must be obtained through trusted token validation. Simply reading fields in a token does not establish that it is valid.
Return 401 for an invalid token, or 403 for a valid token lacking the required permission. Once checks pass, the employee can query stock through Cursor. Any attempt to change stock still requires the server to check the corresponding write permission.
Choose an Access Control Approach
| Scenario | Approach |
|---|---|
| Testing a custom client and server in a controlled environment | Shared token |
| Multiple employees accessing company services through different AI applications | Standard MCP OAuth authorization |
A production OAuth integration requires a real authorization server. The MCP server publishes resource metadata and validates access tokens, while the client handles user authorization and token management. Configuration depends on the identity service in use; implementation code is outside this article's scope.
Reference: MCP authorization specification.
🧱 Security Considerations for Production
An MCP HTTP server can use the Node.js deployment methods covered earlier; there is no need to relearn Nginx or process management. When exposing a production service:
- Use HTTPS to protect tokens and request data, restrict allowed Host values, and validate the request's Origin.
- Validate tokens and business permissions. Do not forward incoming MCP access tokens directly to other business services.
- If using SSE responses, ensure the reverse proxy does not buffer the event stream and allows sufficiently long connections.
❓ Knowledge Check
Q1: Can an MCP server's access token be placed in Vue frontend code?
Do not embed private shared service credentials in frontend code, because browser users can inspect them. A custom AI application should store service credentials securely on its backend or obtain limited-permission tokens through a proper user OAuth flow.
Q2: Do existing access tokens become invalid immediately when an employee revokes an AI application's authorization?
Not necessarily. This depends on the authorization server's revocation mechanism and the MCP server's token validation method. Some tokens can be revoked immediately; others remain valid until expiration. Production services therefore need appropriate token lifetimes and validation methods suited to their security requirements.
🧪 Exercise
Replace MCP_TOKEN in .env.mcp with a new random token, retaining the old token only for this local test.
- Restart the MCP server to activate the new token.
- Temporarily use the old token in the client's
Authorizationheader and verify that the connection is rejected (401). - Restore reading the new token from
.env.mcp, rerun the client, and confirm that P100 stock can be queried successfully.
Observe why the old credentials no longer work after the shared token changes. Delete the old token after testing, and do not commit credentials to Git.
🎉 You now know the basics of access control for an MCP HTTP service and how standard OAuth authorization helps AI applications access external tools securely.
