Spring Security多安全配置问题:JWT接口与dashboard表单登录失效
Spring Security多认证模式配置不生效解决方案
配置失效的核心原因是优先级更高的
ApiWebSecurityConfigurationAdapter没有限定处理的URL范围,默认会接管所有请求,低优先级的表单登录配置永远不会被触发。
具体修改点
- 给
ApiWebSecurityConfigurationAdapter添加请求范围限定,只处理JWT认证相关的/authenticate和/api/**路径,剩余请求流转到下一个配置 - 给表单登录配置类显式指定
@Order(2),保证优先级顺序 - 表单登录配置保留默认会话策略即可,不需要设置无状态,适配表单登录的会话存储需求
修改后完整代码
@EnableWebSecurity public class MultiHttpSecurityConfig { @Autowired private UserDetailsService jwtUserDetailsService; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .userDetailsService(jwtUserDetailsService) .passwordEncoder(passwordEncoder()); } @Bean public PasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance(); } @Configuration @Order(1) public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { @Autowired private JwtRequestFilter jwtRequestFilter; protected void configure(HttpSecurity http) throws Exception { // 新增:限定当前配置只处理JWT相关的两类路径 http.requestMatchers() .antMatchers("/authenticate/**", "/api/**") .and() .csrf().disable() .authorizeRequests() .antMatchers("/authenticate", "/authenticate/**").permitAll() .antMatchers(HttpMethod.GET, "/api/**").permitAll() .anyRequest().authenticated() .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } } @Configuration @Order(2) // 新增:显式指定优先级 public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/dashboard/index.html").authenticated() // 若需要dashboard下所有路径都走认证,可替换为 .antMatchers("/dashboard/**").authenticated() .anyRequest().permitAll() // 其余非dashboard路径可按需调整权限规则 .and() .formLogin(); } } }
效果验证
/authenticate接口所有人可访问:已在第一个配置中配置permitAll,符合需求/api路径GET请求无需授权,其余请求方法需携带有效JWT:已匹配第一个配置的规则,JWT过滤器生效,符合需求- 访问
/dashboard/index.html跳转表单登录页:该路径不会被第一个配置匹配,流转到第二个配置触发表单认证,符合需求
内容的提问来源于stack exchange,提问作者Alexis Yair
相关产品推荐
相关产品推荐

