From 618f24a9acb25222b01dec19e773362bb36c7abb Mon Sep 17 00:00:00 2001 From: xiaoli Date: Tue, 13 May 2025 23:38:19 +0800 Subject: [PATCH] feat: support custom authorization headers, fix #395 --- client/src/lib/hooks/useConnection.ts | 7 ++++++- server/src/index.ts | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/client/src/lib/hooks/useConnection.ts b/client/src/lib/hooks/useConnection.ts index 4ced90e4..501c8359 100644 --- a/client/src/lib/hooks/useConnection.ts +++ b/client/src/lib/hooks/useConnection.ts @@ -297,7 +297,12 @@ export function useConnection({ bearerToken || (await serverAuthProvider.tokens())?.access_token; if (token) { const authHeaderName = headerName || "Authorization"; - headers[authHeaderName] = `Bearer ${token}`; + headers[authHeaderName] = token; + + // Add custom header name as a special request header to let the server know which header to pass through + if (headerName && headerName.toLowerCase() !== "authorization") { + headers["x-custom-auth-header"] = headerName; + } } // Create appropriate transport diff --git a/server/src/index.ts b/server/src/index.ts index c967b60c..766d2df4 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -91,6 +91,15 @@ const createTransport = async (req: express.Request): Promise => { const value = req.headers[key]; headers[key] = Array.isArray(value) ? value[value.length - 1] : value; } + + // If the header "x-custom-auth-header" is present, use its value as the custom header name. + if (req.headers["x-custom-auth-header"] !== undefined) { + const customHeaderName = req.headers["x-custom-auth-header"] as string; + if (req.headers[customHeaderName.toLowerCase()] !== undefined) { + const value = req.headers[customHeaderName.toLowerCase()]; + headers[customHeaderName] = Array.isArray(value) ? value[value.length - 1] : value as string; + } + } console.log(`SSE transport: url=${url}, headers=${Object.keys(headers)}`); @@ -119,6 +128,15 @@ const createTransport = async (req: express.Request): Promise => { const value = req.headers[key]; headers[key] = Array.isArray(value) ? value[value.length - 1] : value; } + + // If the header "x-custom-auth-header" is present, use its value as the custom header name. + if (req.headers["x-custom-auth-header"] !== undefined) { + const customHeaderName = req.headers["x-custom-auth-header"] as string; + if (req.headers[customHeaderName.toLowerCase()] !== undefined) { + const value = req.headers[customHeaderName.toLowerCase()]; + headers[customHeaderName] = Array.isArray(value) ? value[value.length - 1] : value as string; + } + } const transport = new StreamableHTTPClientTransport( new URL(query.url as string),