1. 自定义CORSConfig类
该类实现WebMvcConfigurer接口,重写addCorsMappings方法
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CORSConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowCredentials(true)
.allowedOriginPatterns("*")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.exposedHeaders("*");
}
}
2. 需要注意,SpringSecurityConfig类中处理登录过程中,要启用cors
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// 登录过程的处理
http.csrf(csrf -> csrf.disable())
.addFilterBefore(checkTokenFilter, UsernamePasswordAuthenticationFilter.class)
.formLogin(loginForm -> loginForm
.loginProcessingUrl("/user/login")
.successHandler(loginSuccessHandler)
.failureHandler(loginFailureHandler)
.usernameParameter("username")
.passwordParameter("password"))
.sessionManagement(sessMgr -> sessMgr.sessionCreationPolicy((SessionCreationPolicy.STATELESS))) // 不创建session
.authenticationProvider(authenticationProvider())
.authorizeHttpRequests(authorizeHttpRequests -> authorizeHttpRequests
.requestMatchers(HttpMethod.OPTIONS).permitAll() // 设置需要拦截的请求
.requestMatchers("/user/login").permitAll() // 登录请求放行(不拦截)
.anyRequest().authenticated())// 其它一律请求都需要进行身份认证
.exceptionHandling(exceptionHandling -> exceptionHandling
.authenticationEntryPoint(anonymousAuthentticationHandler) // 匿名无权限访问
.accessDeniedHandler(customerAccessDeniedHandler)) // 认证用户无权限访问
.cors(); // 支持跨域请求
return http.build();
}
特别重要的一点
如果你的security的config里面设置了.formLogin(),那么前台提交就必须要用form表单提交,若使用的axios,需要模拟form提交。原本是表单提交的,后来因为测试改成用Axios提交,结果搞了好久没搞定,找了一下资料才发现是这个问题。
axios.post(url, params, {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})