Spring Boot应用同时配置OAuth2与JWT双认证机制不生效如何解决
问题根因
问题核心是Spring Security多配置链未指定执行优先级,导致请求匹配逻辑不符合预期:
- 多个
WebSecurityConfigurerAdapter实现类没有显式指定@Order注解时,Spring Security会按默认顺序加载,优先级低的配置链没有机会匹配对应路径的请求 - 你当前的JWT配置链仅显式匹配了三个固定路径,且优先级低于OAuth2配置链,所以所有请求都会先被OAuth2配置链处理,非匹配路径也无法进入JWT配置链的逻辑
修复方案
步骤1:给配置链添加优先级注解
@Order值越小配置优先级越高,我们让路径更具体的OAuth2配置链优先级更高,先匹配它负责的路径,剩下的请求再走JWT配置链。
步骤2:调整JWT配置链的匹配规则
不用显式枚举所有需要JWT认证的路径,直接兜底所有未被OAuth2配置链匹配的请求即可,后续新增业务路径也不需要修改配置。
修改后代码
OAuth2配置类
@Configuration @EnableWebSecurity @Order(1) // 优先级更高,先匹配特定路径 public class WebSecurityInfoOAuth2 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http // 仅处理这三个路径的请求 .requestMatchers().antMatchers("/token", "/oauth/**", "/oauth2/**") .and() .authorizeRequests() .antMatchers("/oauth/**", "/oauth2/**").permitAll() .anyRequest().authenticated() .and() // 注意:OAuth2授权码流默认需要Session存储请求状态,如果你确认当前STATELESS配置不影响/token接口的正常运行可以保留,否则改为SessionCreationPolicy.IF_REQUIRED .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .oauth2Login() .userInfoEndpoint() .userService(oauthUserService) .and() .successHandler(new AuthenticationSuccessHandler() { // 你的自定义成功返回JWT逻辑 }); } }
JWT配置类
@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) @Order(2) // 优先级更低,作为兜底配置 public class WebSecurityInfoJWT extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.csrf().disable() // 兜底所有未被上一个配置链匹配的请求,不用逐个枚举业务路径 .requestMatchers().anyRequest() .and() .authorizeRequests() .anyRequest().authenticated() .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS); httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); } }
生效后效果
- 访问
/token、/oauth/**、/oauth2/**路径会走OAuth2配置链,只有/token会触发OAuth2认证逻辑,其他两个路径直接放行 - 其他所有路径(包括
/hello1、/hello2等)都会走JWT配置链,会进入你的jwtRequestFilter进行令牌校验,不会重定向到OAuth2登录页
内容的提问来源于stack exchange,提问作者Priyshrm
相关产品推荐
相关产品推荐

