如何基于Spring Security WebFlux自定义OAuth2登录重定向端点基础URI
Got it, let's break down exactly how to customize the OAuth2 login redirect base URI in Spring WebFlux—since the reactive stack works a bit differently than the Servlet stack, we'll leverage the authorizationRequestResolver and authenticationMatcher components you mentioned.
Step 1: Customize the Authorization Request Resolver
This component handles the URI that triggers the OAuth2 authorization flow (the one users hit to start logging in with a provider like GitHub). By default, it uses /oauth2/authorization/{registrationId}, but we can override the base URI:
@Bean public ServerOAuth2AuthorizationRequestResolver customAuthRequestResolver(ClientRegistrationRepository clientRegistrationRepo) { DefaultServerOAuth2AuthorizationRequestResolver resolver = new DefaultServerOAuth2AuthorizationRequestResolver(clientRegistrationRepo); // Replace with your desired base URI here resolver.setAuthorizationRequestBaseUri("/my-custom-oauth2/authorization"); return resolver; }
Step 2: Configure the Authentication Matcher for Callback URIs
Next, we need to update the matcher that handles the callback from the OAuth2 provider (the endpoint where the provider sends the authorization code). The default is /login/oauth2/code/{registrationId}, so we'll point this to our custom base URI:
@Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http, ServerOAuth2AuthorizationRequestResolver customAuthRequestResolver) { http .authorizeExchange(exchanges -> exchanges .anyExchange().authenticated() ) .oauth2Login(oauth2 -> oauth2 // Attach our custom authorization request resolver .authorizationRequestResolver(customAuthRequestResolver) // Set up the matcher for the custom callback URI .authenticationMatcher(new PathPatternParserServerWebExchangeMatcher("/my-custom-oauth2/code/{registrationId}")) ); return http.build(); }
Step 3: Update Client Redirect URI Configuration
Don't forget to update your OAuth2 client's redirect URI in your application config to match the new callback endpoint. For example, in application.yml:
spring: security: oauth2: client: registration: github: client-id: your-client-id client-secret: your-client-secret redirect-uri: "{baseUrl}/my-custom-oauth2/code/github"
What This Does
- The
authorizationRequestResolverchanges the initiation URI from/oauth2/authorization/githubto/my-custom-oauth2/authorization/github. - The
authenticationMatchertells Spring Security to listen for the provider's callback at/my-custom-oauth2/code/githubinstead of the default/login/oauth2/code/github.
This setup fully replaces the default OAuth2 login base URIs with your custom ones, adapted perfectly for WebFlux's reactive model.
内容的提问来源于stack exchange,提问作者Saurabh Gour

