Created
July 7, 2025 20:59
-
-
Save jbasdf/1c379a3ab38c9a37e25e2a40cdad03c2 to your computer and use it in GitHub Desktop.
Wrapper for Cloudflare OAuthProvider with custom handler for /.well-known/oauth-authorization-server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default { | |
async fetch(request: Request, env: Env, ctx: ExecutionContext) { | |
// OAuthProvider provides a generic .well-known/oauth-authorization-server | |
// We capture the request here so that we can include the providerId in the response | |
// This overrides some of the funcitionality provided by the OAuthProvider | |
// If any endpoints are changed please ensure to review the code in handleWellKnown. | |
if (request.url.includes('/.well-known/oauth-authorization-server/mcp')) { | |
return handleWellKnown(request); | |
} | |
// Export the OAuth handler as the default | |
const oauthWrapper = new OAuthProvider({ | |
apiHandlers: { | |
// @ts-ignore | |
'/sse': sseHandler, | |
// @ts-ignore | |
'/mcp': mcpHandler, | |
}, | |
// @ts-ignore | |
defaultHandler: app, | |
authorizeEndpoint: '/authorize', | |
tokenEndpoint: '/token', | |
clientRegistrationEndpoint: "/register", | |
}); | |
const response = await oauthWrapper.fetch(request, env, ctx); | |
// If the provider is using Javascript without allowing credentials this won't work | |
// However, we can still set the cookie for the providerId for clients that support it. | |
const providerId = extractProviderId(request); | |
if (providerId) { | |
const cookieValue = `providerId=${providerId}; Path=/; HttpOnly; SameSite=Strict; Max-Age=3600`; | |
response.headers.set('Set-Cookie', cookieValue); | |
} | |
return response; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment