近期,在做项目的过程中遇到了前后端分离的权限认证问题,通过查阅资料,找到了解决方案,记录一下。
WebSecurityConfig
@Bean
public PasswordEncoder passwordEncoder(){
// 使用BCrypt加密密码
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
// 允许所有人访问
.authorizeRequests()
.antMatchers("/reservoirs/user/userLogin","/logout","/reservoirs/user/register")
.permitAll()
.anyRequest()
.authenticated()
.and()
// 禁用缓存
.headers()
.cacheControl();
// 登录授权过滤器
http.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
//添加自定义未登录未授权、返回
http.exceptionHandling()
//.accessDeniedHandler(restAccessDeniedHandler);
.authenticationEntryPoint(authenticationEntryPoint);
}
//跨域请求
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
configuration.setAllowCredentials(true);
configuration.addAllowedOrigin("*");
configuration.addAllowedHeader("*");
configuration.add