Spring处理跨域请求(含有SpringBoot方式)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24084925/article/details/55049300

一次正常的请求

最近别人需要调用我们系统的某一个功能,对方希望提供一个api让其能够更新数据。由于该同学是客户端开发,于是有了类似以下代码。


   
   
  1. @RequestMapping(method = RequestMethod.POST, value = "/update.json", produces = MediaType.APPLICATION_JSON_VALUE)
  2. public @ResponseBody Contacter update(@RequestBody Contacter contacterRO) {
  3. logger.debug("get update request {}", contacterRO.toString());
  4. if (contacterRO.getUserId() == 123) {
  5. contacterRO.setUserName("adminUpdate-wangdachui");
  6. }
  7. return contacterRO;
  8. }

客户端通过代码发起http请求来调用。接着,该同学又提出:希望通过浏览器使用js调用,于是便有跨域问题。

为何跨域

前端请求于后端处理符合三个要求(同一域名,同一端口,同一协议)下,即可访问,有一个不符合就会出现跨域问题。

  • 例如:以下代码再本域名下可以通过js代码正常调用接口

   
   
  1. ( function() {
  2. var url = "http://localhost:8080/api/Home/update.json";
  3. var data = {
  4. "userId": 123,
  5. "userName": "wangdachui"
  6. } ;
  7. $.ajax({
  8. url: url,
  9. type: 'POST',
  10. dataType: 'json',
  11. data: $.toJSON(data),
  12. contentType: 'application/json'
  13. }).done(function(result) {
  14. console.log("success");
  15. console.log(result);
  16. }).fail(function() {
  17. console.log("error");
  18. })
  19. })()

输出为:


   
   
  1. Object {userId: 123, userName: "adminUpdate-wangdachui"}
  • 但是在其他域名下访问则出错:


   
   
  1. OPTIONS http://localhost:8080/api/Home/update.json
  2. XMLHttpRequest cannot load http://localhost:8080/api/Home/update.json. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403.

解决方案

JSONP

使用jsonp来进行跨域是一种比较常见的方式,但是在接口已经写好的情况下,无论是服务端还是调用端都需要进行改造且要兼容原来的接口,工作量偏大,于是我们考虑其他方法。

CORS协议

按照参考资料的说法:每一个页面需要返回一个名为‘Access-Control-Allow-Origin’的HTTP头来允许外域的站点访问。你可以仅仅暴露有限的资源和有限的外域站点访问。在COR模式中,访问控制的职责可以放到页面开发者的手中,而不是服务器管理员。当然页面开发者需要写专门的处理代码来允许被外域访问。 我们可以理解为:如果一个请求需要允许跨域访问,则需要在http头中设置Access-Control-Allow-Origin来决定需要允许哪些站点来访问。如假设需要允许www.foo.com这个站点的请求跨域,则可以设置:Access-Control-Allow-Origin:http://www.foo.com。或者Access-Control-Allow-Origin: * 。 CORS作为HTML5的一部分,在大部分现代浏览器中有所支持。

CORS具有以下常见的header


   
   
  1. Access-Control-Allow-Origin: http://foo.org
  2. Access-Control-Max-Age: 3628800
  3. Access-Control-Allow-Methods: GET,PUT, DELETE
  4. Access-Control-Allow-Headers: content-type
  5. "Access-Control-Allow-Origin"表明它允许"http://foo.org"发起跨域请求
  6. "Access-Control-Max-Age"表明在3628800秒内,不需要再发送预检验请求,可以缓存该结果
  7. "Access-Control-Allow-Methods"表明它允许GET、PUT、DELETE的外域请求
  8. "Access-Control-Allow-Headers"表明它允许跨域请求包含content-type

CORS基本流程

首先发出预检验(Preflight)请求,它先向资源服务器发出一个OPTIONS方法、包含“Origin”头的请求。该回复可以控制COR请求的方法,HTTP头以及验证等信息。只有该请求获得允许以后,才会发起真实的外域请求。

Spring MVC支持CORS


   
   
  1. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403.

从以上这段错误信息中我们可以看到,直接原因是因为请求头中没有Access-Control-Allow-Origin这个头。于是我们直接想法便是在请求头中加上这个header。服务器能够返回403,表明服务器确实对请求进行了处理。

需要注意的是,如果要发送CookieAccess-Control-Allow-Origin就不能设为星号,必须指定明确的、与请求网页一致的域名。同时,Cookie依然遵循同源政策,只有用服务器域名设置的Cookie才会上传,其他域名的Cookie并不会上传,且(跨源)原网页代码中的document.cookie也无法读取服务器域名下的Cookie


MVC 拦截器

首先我们配置一个拦截器来拦截请求,将请求的头信息打日志。


   
   
  1. DEBUG requestURL:/api/Home/update.json
  2. DEBUG method:OPTIONS
  3. DEBUG header host:localhost:8080
  4. DEBUG header connection:keep-alive
  5. DEBUG header cache-control:max-age=0
  6. DEBUG header access-control-request-method:POST
  7. DEBUG header origin:null
  8. DEBUG header user-agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36
  9. DEBUG header access-control-request-headers:accept, content-type
  10. DEBUG header accept:*/*
  11. DEBUG header accept-encoding:gzip, deflate, sdch
  12. DEBUG header accept-language:zh-CN,zh;q=0.8,en;q=0.6

在postHandle里打印日志发现,此时response的status为403。跟踪SpringMVC代码发现,在org.springframework.web.servlet.DispatcherServlet.doDispatch中会根据根据request来获取HandlerExecutionChain,SpringMVC在获取常规的处理器后会检查是否为跨域请求,如果是则替换原有的实例。


   
   
  1. @Override
  2. public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
  3. Object handler = getHandlerInternal(request);
  4. if (handler == null) {
  5. handler = getDefaultHandler();
  6. }
  7. if (handler == null) {
  8. return null;
  9. }
  10. // Bean name or resolved handler?
  11. if (handler instanceof String) {
  12. String handlerName = (String) handler;
  13. handler = getApplicationContext().getBean(handlerName);
  14. }
  15. HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);
  16. if (CorsUtils.isCorsRequest(request)) {
  17. CorsConfiguration globalConfig = this.corsConfigSource.getCorsConfiguration(request);
  18. CorsConfiguration handlerConfig = getCorsConfiguration(handler, request);
  19. CorsConfiguration config = (globalConfig != null ? globalConfig.combine(handlerConfig) : handlerConfig);
  20. executionChain = getCorsHandlerExecutionChain(request, executionChain, config);
  21. }
  22. return executionChain;
  23. }

检查的方法也很简单,即检查请求头中是否有origin字段


   
   
  1. public static boolean isCorsRequest(HttpServletRequest request) {
  2. return (request.getHeader(HttpHeaders.ORIGIN) != null);
  3. }

请求接着会交由 HttpRequestHandlerAdapter.handle来处理,根据handle不同,处理不同的逻辑。前面根据请求头判断是一个跨域请求,获取到的Handler为PreFlightHandler,其实现为:


   
   
  1. @Override
  2. public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
  3. corsProcessor.processRequest(this.config, request, response);
  4. }

继续跟进


   
   
  1. @Override
  2. public boolean processRequest(CorsConfiguration config, HttpServletRequest request, HttpServletResponse response)
  3. throws IOException {
  4. if (!CorsUtils.isCorsRequest(request)) {
  5. return true;
  6. }
  7. ServletServerHttpResponse serverResponse = new ServletServerHttpResponse(response);
  8. ServletServerHttpRequest serverRequest = new ServletServerHttpRequest(request);
  9. if (WebUtils.isSameOrigin(serverRequest)) {
  10. logger.debug("Skip CORS processing, request is a same-origin one");
  11. return true;
  12. }
  13. if (responseHasCors(serverResponse)) {
  14. logger.debug("Skip CORS processing, response already contains \"Access-Control-Allow-Origin\" header");
  15. return true;
  16. }
  17. boolean preFlightRequest = CorsUtils.isPreFlightRequest(request);
  18. if (config == null) {
  19. if (preFlightRequest) {
  20. rejectRequest(serverResponse);
  21. return false;
  22. }
  23. else {
  24. return true;
  25. }
  26. }
  27. return handleInternal(serverRequest, serverResponse, config, preFlightRequest);
  28. }

此方法首先会检查是否为跨域请求,如果不是则直接返回,接着检查是否同一个域下,或者response头里是否具有Access-Control-Allow-Origin字段或者request里是否具有Access-Control-Request-Method。如果满足判断条件,则拒绝这个请求。 由此我们知道,可以通过在检查之前设置response的Access-Control-Allow-Origin头来通过检查。我们在拦截器的preHandle的处理。加入如下代码:


   
   
  1. response.setHeader("Access-Control-Allow-Origin", "*");

此时浏览器中OPTIONS请求返回200。但是依然报错:


   
   
  1. Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

我们注意到:在request的请求头里有Access-Control-Request-Headers:accept, content-type,但是这个请求头的中没有,此时浏览器没有据需发送请求。尝试在response中加入:


   
   
  1. response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

执行成功:Object {userId: 123, userName: “adminUpdate-wangdachui”}。

至此:我们通过分析原理使SpringMVC实现跨域,原有实现以及客户端代码不需要任何改动。

1、SpringMVC 4

  • 此外,在参考资料2中,SpringMVC4提供了非常方便的实现跨域的方法。
  • 在requestMapping中使用注解。 @CrossOrigin(origins = “http://localhost:9000”)
  • 全局实现 .定义类继承WebMvcConfigurerAdapter

   
   
  1. public class CorsConfigurerAdapter extends WebMvcConfigurerAdapter{
  2. @Override
  3. public void addCorsMappings( CorsRegistry registry) {
  4. registry.addMapping("/api/*").allowedOrigins("*");
  5. }
  6. }

将该类注入到容器中:


   
   
  1. <bean class="com.tmall.wireless.angel.web.config.CorsConfigurerAdapter"></bean>

参考资料


2、自己写一个类似于FILTER的文件,加载一下它
import java.io.IOException;  

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

public class CorsFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
response.addHeader(
“Access-Control-Allow-Origin”, “*”);
response.addHeader(
“Access-Control-Allow-Methods”,
“GET, POST, PUT, DELETE, OPTIONS”);
response.addHeader(
“Access-Control-Allow-Headers”,
“origin, content-type, accept, x-requested-with, sid, mycustom, smuser”);
filterChain.doFilter(request, response);
}
}

复制代码

修改web.xml

复制代码
<filter>  
  <filter-name>CorsFilter</filter-name>  
  <filter-class>com.interfaceservice.filter.CorsFilter</filter-class>  
</filter>  
<filter-mapping>  
  <filter-name>CorsFilter</filter-name>  
  <url-pattern>/*</url-pattern>  
</filter-mapping>  


3、
若是SpringBoot则简单的多:

在application.java文件下添加:

   
   
  1. @Bean
  2. public WebMvcConfigurer corsConfigurer() {
  3. return new WebMvcConfigurerAdapter() {
  4. @Override
  5. public void addCorsMappings(CorsRegistry registry) {
  6. registry.addMapping( "/**")
  7. .allowedOrigins( "*")
  8. .allowedMethods( "PUT", "DELETE", "GET", "POST")
  9. .allowedHeaders( "*")
  10. .exposedHeaders( "access-control-allow-headers",
  11. "access-control-allow-methods",
  12. "access-control-allow-origin",
  13. "access-control-max-age",
  14. "X-Frame-Options")
  15. .allowCredentials( false).maxAge( 3600);
  16. }
  17. };
  18. }
即可



版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24084925/article/details/55049300

猜你喜欢

转载自blog.csdn.net/liyang_com/article/details/83049575