贴下我最后的配置类吧,我使用的也是第一种方案。因为自己写的过滤器,formLogin,httpBasic,这两个人家封装好的处理方案,我全部禁用了
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationProvider customAuthenticationProvider;
@Autowired
private RedisTemplate redisTemplate;
/**
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.authorizeRequests();
registry.and()
.formLogin().disable()
.authorizeRequests()
.antMatchers("/user/login").permitAll()
.antMatchers("/user/register").permitAll()
.antMatchers("/admin").hasAnyRole("ADMIN")
// 任何请求 需要身份认证
.anyRequest().authenticated()
.and()
// 添加一个过滤 所有访问 /login 的请求给JWTLoginFilter处理 这个类处理所有的JWT相关内容
.addFilterBefore(new JWTLoginFilter("/user/login", HttpMethod.POST.toString(),authenticationManager(),redisTemplate), UsernamePasswordAuthenticationFilter.class)
// 添加一个过滤器,验证其他请求是否合法
.addFilterBefore(new JWTAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class)
// 关闭跨站请求防护
.csrf().disable()
// 前后端分离采用JWT 不需要session
.sessionManagement().disable();
}
/**
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 使用自定义身份验证组件
auth.authenticationProvider(customAuthenticationProvider);
}
@Bean
public Argon2PasswordEncoder passwordEncoder() {
return new Argon2PasswordEncoder();
}
}