Spring Authorization Server 1.0.0登录重定向异常问题求助
问题描述
使用Spring Authorization Server,0.3.1版本时授权码流程功能正常,升级至1.0.0版本后,完成登录操作本应重定向至/authorized?code=,但始终被重定向回/login页面。
核心原因
- 重复登录配置冲突:在
AuthorizationServerConfig的高优先级SecurityFilterChain中,配置了formLogin(Customizer.withDefaults())和oauth2Login(Customizer.withDefaults()),这会覆盖SecurityConfig中自定义的登录成功处理器,导致登录成功后无法正确处理授权请求的重定向状态。 - 授权服务器职责边界模糊:1.0.0版本后,Spring Authorization Server对配置职责划分更清晰,授权服务器的
SecurityFilterChain仅需负责OAuth2授权相关端点的安全,用户登录等通用认证逻辑应统一放在主SecurityConfig中处理。
修复步骤
- 移除授权服务器中的登录配置:删除
AuthorizationServerConfig内authorizationServerSecurityFilterChain方法中的formLogin和oauth2Login配置,避免与主安全配置冲突。 - 确保主安全配置的登录处理器兼容授权流程:
SecurityConfig中的自定义登录成功处理器需保留默认的重定向逻辑(或调用super.onAuthenticationSuccess),确保能正确跳转回授权请求的回调地址。 - 验证客户端重定向URI配置:确认
RegisteredClient中的redirectUri与实际回调地址一致,且主安全配置已允许该地址的匿名访问(你的配置中已设置/authorized为permitAll,这部分无需修改)。
修改后的代码示例
AuthorizationServerConfig 中的 SecurityFilterChain
@Bean @Order(Ordered.HIGHEST_PRECEDENCE) public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); RequestMatcher endpointsMatcher = authorizationServerConfigurer.getEndpointsMatcher(); http .securityMatcher(endpointsMatcher) .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) .authorizeHttpRequests(auth -> { auth.anyRequest().authenticated(); }) .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt) .apply(authorizationServerConfigurer); return http.build(); }
验证登录处理器逻辑
确保FormLoginAuthenticationSuccessHandler和FederatedIdentityAuthenticationSuccessHandler中,若自定义了逻辑,需调用默认的重定向处理,示例如下:
@Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { // 自定义业务逻辑 // ... // 调用默认处理,确保授权流程的重定向正常 super.onAuthenticationSuccess(request, response, authentication); }
关键说明
Spring Authorization Server 1.0.0版本对配置结构进行了优化,要求授权服务器的安全配置专注于自身端点,通用认证逻辑统一由主安全配置管理,避免重复配置导致的状态丢失或重定向异常。
内容的提问来源于stack exchange,提问作者Andrew Zabur
相关产品推荐
相关产品推荐

