jdk1.7+Spring 4.3跨域问题解决

遗留项目 jdk1.7.0_79 + spring mvc (4.3.2)

接口为了支持跨域访问 Nginx做了如下的配置

    location /cgi/myCollections {
        add_header Access-Control-Allow-Credentials true;
        add_header Access-Control-Allow-Origin $http_origin;
        proxy_pass http://localhost:8081/cgi/myCollections;
    }
    

但是跨域访问的时候 Status Code: 403 Forbidden

1.  Request URL: http://aaa.foo.com/cgi/myCollections?type=STK&page=1&size=1000
    
2.  Request Method: OPTIONS
    
3.  Status Code: 403 Forbidden

同时Console中错误信息如下

Access to XMLHttpRequest at 'http://aaa.foo.com/cgi/myCollections?type=STK&page=1&size=1000' from origin 'http://bbb.foo.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

为什么Nginx明明已经配置了Access-Control-Allow-Origin 怎么还会报这样的错呢

于是尝试在代码中显式添加@CrossOrigin 看看是否有同样的问题
但是编译就报错了

 annotation org.springframework.web.bind.annotation.CrossOrigin is missing value for the attribute 

原因:jdk的bug 得升级jdk

It says that this was a known and resolved issue in java 1.8 and has been back-ported to java 7. So, Update to the latest java 7 version (7u80) or Java 8 version.
https://stackoverflow.com/que...

于是升级了到jdk1.7.0_80 果然能正常编译了 于是取消了Nginx配置 跨域请求正常

引申问题

  • 为什么代码中配置就可以 但是Nginx配置就不行呢

原因: 代码中做了限制 详见org.springframework.web.cors.DefaultCorsProcessor#processRequest


boolean preFlightRequest = CorsUtils.isPreFlightRequest(request);
if (config == null) {
    if (preFlightRequest) {
        rejectRequest(serverResponse);
        return false;
    }
    else {
        return true;
    }
}

这种情况下Nginx需要如下配置

location /cgi/myCollections {
    add_header Access-Control-Allow-Credentials true;
    add_header Access-Control-Allow-Origin $http_origin;
    add_header Access-Control-Allow-Headers UID;
    proxy_set_header Host 'bbb.foo.com';
    proxy_pass http://localhost:8081/cgi/myCollections;
}

参考文档

https://spring.io/blog/2015/0...

你可能感兴趣的:(jdk7,cors)