You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security 6中如何配置自定义OAuth2AuthenticationSuccessHandler

Spring Security 6 配置自定义OAuth2AuthenticationSuccessHandler

在Spring Security 6中,只需调整oauth2Login的配置方式,通过lambda表达式直接指定自定义成功处理器即可,无需使用Customizer.withDefaults()。

修改你的filterChain方法,将原代码中的:

.oauth2Login(Customizer.withDefaults())

替换为:

.oauth2Login(oauth2 -> oauth2.successHandler(oAuth2AuthenticationSuccessHandler))

完整的filterChain方法代码如下:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

    http
            .authorizeHttpRequests((authz) -> authz
                    .requestMatchers("/toto",
                            "/titi",
                            "/v3/api-docs/**",
                            "/swagger-ui/**",
                            "/swagger-ui.html",
                            "/sitemap.xml")
                    .permitAll()
                    .anyRequest().authenticated())
            .oauth2Login(oauth2 -> oauth2.successHandler(oAuth2AuthenticationSuccessHandler))
            .cors(Customizer.withDefaults())
            .csrf(csrf -> csrf.disable()); // 若需保持Spring Security 5的CSRF配置,添加此行

    return http.addFilterBefore(tokenAuthenticationFilter(),
                    UsernamePasswordAuthenticationFilter.class)
            .build();
}

说明

  • Spring Security 6采用lambda链式配置风格,通过oauth2Login的lambda参数可直接访问OAuth2登录配置器,设置successHandler即可注入自定义处理器。
  • Spring Security 6默认开启CSRF防护,如果你需要延续Spring Security 5中关闭CSRF的配置,记得加上.csrf(csrf -> csrf.disable())。

内容的提问来源于stack exchange,提问作者Samuel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 18:47:12