您的位置:首页 > 编程语言 > Java开发

[置顶] spring boot项目实战:跨域问题解决

2017-09-26 13:42 906 查看

背景

前后端分离架构,前端anglerjs,后端spring boot,使用shiro作为权限控制,已配置通用跨域请求支持。

前端调用接口时部分情况正常,部分情况出现跨域请求不支持情况,错误信息如下:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'xxxx' is therefore not allowed access.


配置错了?

首先,想到的就是对跨域请求支持的配置是错误的,尝试着替换不同的跨域支持配置,有以下几种:

1、继承WebMvcConfigurerAdapter

@Configuration

public class AppConfig extends WebMvcConfigurerAdapter {

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true).allowedHeaders("Origin, X-Requested-With, Content-Type, Accept")
.allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS")
.maxAge(3600);
}
}


2、配置WebMvcConfigurer

@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*")
.allowedMethods("*").allowedHeaders("*")
.allowCredentials(true)
.exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L);
}
};
}




CORS support in Spring Framework内的方式都尝试了一遍,发现问题仍然未解决,看到文档内的一个点

If you are using Spring Security, make sure to enable CORS at Spring Security level as well to allow it to leverage the configuration defined at Spring MVC level.

大概意思就是使用Spring Security要进行特殊的配置来支持CORS。而当前项目内使用的是shiro,是不是权限控制导致的问题?检查shiro相关代码,果然找到了问题,在loginFilter内会判断如果未登录,就通过response写回未登录提示,代码如下:

Subject subject = SecurityUtils.getSubject();
if (!subject.isAuthenticated()) {
HttpServletResponse resp = (HttpServletResponse) response;
String contentType = "application/json";
resp.setContentType(contentType);
resp.setCharacterEncoding("UTF-8");

Map<String, String> map = Maps.newLinkedHashMap();
map.put("code", "xxx");

4000
map.put("msg", "xxx");
String result = JacksonHelper.toJson(map);
PrintWriter out = resp.getWriter();
try{
out.print(result);
out.flush();
} finally {
out.close();
}
return;
}


那就添加上跨域支持

resp.setHeader("Access-Control-Allow-Credentials", "true");
resp.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));


本来以为ok了,但是前端是不报错了,但并不能获得对应接口期望的结果,而是一直收到

{"code":"xxx","msg":"xxx"}


显然是被登录拦截了,但是明明已经登录,而且有的接口可以正常通过登录拦截,为什么部分接口会出现不能登录的情况呢?

明明登录了,为什么被loginFilter拦截?

遇到了问题就要想办法解决,首先就是怀疑客户端sessionId未被正常保存,在loginFilter内添加日志打印sessionID,发现每次的sessionID都不一样,问题清晰了一些,前端并未正确的保持登录状态,对比前端两个调用接口的代码,发现正常的是get请求,post请求不正常,通过在网上搜索,发现ajax post跨域请求时,默认是不携带浏览器的cookie的,也就是每次请求都会生成一个新的session,因此post请求都被登录拦截。解决办法如下:

$.ajax({
type:"POST",
url:"",
data:{},
crossDomain:true,
xhrFields: {  withCredentials: true  },
success:function(data){

},
error:function(data){

}
})


配置crossDomain:true 和 xhrFields: { withCredentials: true }就可以让请求正常携带cookie。

一个完整可用方案

1、配置支持跨域请求(多种方式自由选择,推荐使用下面的方式)

@Configuration
public class WebConfig {

/**
* 跨域请求支持
*/
@Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedOrigins("*") .allowedMethods("*").allowedHeaders("*") .allowCredentials(true) .exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L); } }; }}


2、前端ajax post请求时添加xhrFields: { withCredentials: true }

$.ajax({
type:"POST",
url:"",
data:{},
crossDomain:true,
xhrFields: {  withCredentials: true  },
success:function(data){

},
error:function(data){

}
})


3、检查权限控制代码,看是否有特殊处理的地方,未添加跨域支持。如上文所提,登录拦截直接通过response写回未登录提示;

使用spring-security框架时也要添加特殊配置,如下:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()...
}
}


解决跨域的本质就是在返回头内添加Access-Control-Allow-Origin,实现方式有多种,spring体系内解决跨域可参考CORS support in Spring Framework,很全面的介绍了各种场景。使用权限框架时,要注意权限框架本身的CORS支持。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: