@@ -317,8 +317,44 @@ export class AuthPlugin implements Plugin {
317317 }
318318 } ) ;
319319
320+ // OIDC / OAuth 2.0 Authorization Server Metadata (RFC 8414) and
321+ // OpenID Connect Discovery 1.0 require the well-known documents to be
322+ // served from the **root** of the issuer URL — not under our auth
323+ // basePath. `@better-auth/oauth-provider` ships dedicated helpers for
324+ // this case (`oauthProviderAuthServerMetadata` /
325+ // `oauthProviderOpenIdConfigMetadata`) which we mount here so external
326+ // OIDC clients can discover the IdP at the canonical paths.
327+ if ( this . options . plugins ?. oidcProvider ) {
328+ void this . registerOidcDiscoveryRoutes ( rawApp , ctx ) . catch ( ( error ) => {
329+ ctx . logger . error ( 'Failed to register OIDC discovery routes' , error as Error ) ;
330+ } ) ;
331+ }
332+
320333 ctx . logger . info ( `Auth routes registered: All requests under ${ basePath } /* forwarded to better-auth` ) ;
321334 }
335+
336+ /**
337+ * Mount the OIDC / OAuth 2.0 well-known discovery documents at the root
338+ * URL. Required by RFC 8414 §3 and OpenID Connect Discovery 1.0 §4 — the
339+ * documents must live at `/.well-known/{oauth-authorization-server,openid-configuration}`
340+ * relative to the issuer, not under the auth basePath.
341+ */
342+ private async registerOidcDiscoveryRoutes ( rawApp : any , ctx : PluginContext ) : Promise < void > {
343+ const auth = await this . authManager ! . getAuthInstance ( ) ;
344+ const { oauthProviderAuthServerMetadata, oauthProviderOpenIdConfigMetadata } = await import (
345+ '@better-auth/oauth-provider'
346+ ) ;
347+
348+ const authServerHandler = oauthProviderAuthServerMetadata ( auth as any ) ;
349+ const openidConfigHandler = oauthProviderOpenIdConfigMetadata ( auth as any ) ;
350+
351+ rawApp . get ( '/.well-known/oauth-authorization-server' , ( c : any ) => authServerHandler ( c . req . raw ) ) ;
352+ rawApp . get ( '/.well-known/openid-configuration' , ( c : any ) => openidConfigHandler ( c . req . raw ) ) ;
353+
354+ ctx . logger . info (
355+ 'OIDC discovery endpoints mounted at /.well-known/{oauth-authorization-server,openid-configuration}' ,
356+ ) ;
357+ }
322358}
323359
324360
0 commit comments