问题描述: 本人在做springboot项目时,前端用的是vue框架,然后使用ajax与后端通信,但是前端首先会发一个Option跨域请求,我的后端没有对这个进行处理,前端具体报错见下图。由于我后端加了security jwt token机制,所以网上其他人的解决方案都缺少了security类的具体设置,导致还是会跨域,查询了大量资料后发现只需要在security上加一些字段就可以解决,亲测有效。
解决方案
- 在security中添加跨域处理函数
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//...省略
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//使用JWT,不需要csrf
http.csrf()
.disable()
//基于token,不需要session
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
//允许所有跨域验证的option请求
.antMatchers(HttpMethod.OPTIONS).permitAll() //允许所有options请求,即js跨域请求不拦截
//允许登录和注册访问
.antMatchers("/user/login","/user/register","/user/captcha").permitAll()
//除上面外,所有请求都要求认证
.anyRequest()
.authenticated()
.and()
//设置javascript跨域验证配置,
.cors().configurationSource(CorsConfigurationSource())
.and()
//禁用缓存
.headers()
.cacheControl();
//添加jwt 登录授权过滤器
http.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
//添加自定义未授权和未登录结果返回
http.exceptionHandling()
.accessDeniedHandler(restfulAccessDeniedHandler)
.authenticationEntryPoint(restAuthenticationEntryPoint);
}
private CorsConfigurationSource CorsConfigurationSource() {
CorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); //同源配置,*表示任何请求都视为同源,若需指定ip和端口可以改为如“localhost:8080”,多个以“,”分隔;
corsConfiguration.addAllowedHeader("*");//header,允许哪些header,本案中使用的是token,此处可将*替换为token;
corsConfiguration.addAllowedMethod("*"); //允许的请求方法,PSOT、GET等
((UrlBasedCorsConfigurationSource) source).registerCorsConfiguration("/**",corsConfiguration); //配置允许跨域访问的url
return source;
}
}