@@ -4,7 +4,8 @@ import { withAuthContext } from "./auth-context";
44export function withMcpAuth (
55 handler : ( req : Request ) => Response | Promise < Response > ,
66 verifyToken : (
7- req : Request
7+ req : Request ,
8+ bearerToken ?: string
89 ) => AuthInfo | undefined | Promise < AuthInfo | undefined > ,
910 {
1011 required = false ,
@@ -17,13 +18,21 @@ export function withMcpAuth(
1718 return async ( req : Request ) => {
1819 const origin = new URL ( req . url ) . origin ;
1920
20- const authInfo = await verifyToken ( req ) ;
21+ const authHeader = req . headers . get ( "Authorization" ) ;
22+ const [ type , token ] = authHeader ?. split ( " " ) || [ ] ;
23+
24+ // Only support bearer token as per the MCP spec
25+ // https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization#2-6-1-token-requirements
26+ const bearerToken = type ?. toLowerCase ( ) === "bearer" ? token : undefined ;
27+
28+ const authInfo = await verifyToken ( req , bearerToken ) ;
29+
2130 if ( required && ! authInfo ) {
22- return Response . json (
23- {
31+ return new Response (
32+ JSON . stringify ( {
2433 error : "unauthorized_client" ,
2534 error_description : "No authorization provided" ,
26- } ,
35+ } ) ,
2736 {
2837 status : 401 ,
2938 headers : {
@@ -38,8 +47,11 @@ export function withMcpAuth(
3847 }
3948
4049 if ( authInfo . expiresAt && authInfo . expiresAt < Date . now ( ) / 1000 ) {
41- return Response . json (
42- { error : "invalid_token" , error_description : "Authorization expired" } ,
50+ return new Response (
51+ JSON . stringify ( {
52+ error : "invalid_token" ,
53+ error_description : "Authorization expired" ,
54+ } ) ,
4355 {
4456 status : 401 ,
4557 headers : {
0 commit comments