SpringBoot解决跨域请求拦截

匿名 (未验证) 提交于 2019-12-02 21:42:56

同源策略:判断是否是同源的,主要看这三点,协议,ip,端口。

同源策略就是浏览器出于网站安全性的考虑,限制不同源之间的资源相互访问的一种政策。

比如在域名https://www.baidu.com下,脚本不能够访问https://www.sina.com源下的资源,否则将会被浏览器拦截。

注意两点:

1.必须是脚本请求,比如AJAX请求。

但是如下情况不会产生跨域拦截

<img src="xxx"/> <a href='xxx"> </a>

2.跨域拦截是前端请求已经发出,并且在后端返回响应时检查相关参数,是否允许接收后端请求。

本文主要讲解SpringBoot解决跨域请求拦截的问题。

搭建项目

这里创建两个web项目,web1 和 web2.

web2项目请求web1项目的资源。

这里只贴关键代码,完整代码参考GitHub

WEB2

创建一个Controller返回html页面

@Slf4j @Controller public class HomeController {      @RequestMapping("/index")     public String home(){         log.info("/index");          return "/home";     } }

html页面 home.html

这里创建了一个按钮,按钮按下则请求资源:"http://localhost:8301/hello"

<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>web2</title>      <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">     </script>      <script>         $(function () {                          $("#testBtn").click(function () {                 console.log("testbtn ...");                 $.get("http://localhost:8301/hello",function(data,status){                     alert("数据: " + data + "\n状态: " + status);                 });             })                      })      </script> </head> <body>     web2     <button id="testBtn">测试</button> </body> </html>

WEB1

@Slf4j @RestController public class Web1Controller {      @RequestMapping("/hello")     public String hello(){         log.info("hello ");         return "hello," + new Date().toString();     } }

WEB1Ϊ8301

WEB2Ϊ8302

测试

在web1还没有配置允许跨域访问的情况下

按下按钮,将会出现错误。显示Header中没有Access-Control-Allow-Origin

Access to XMLHttpRequest at 'http://localhost:8301/hello' from origin 'http://localhost:8300' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

WEB1添加允许跨域请求,通过实现WebMvcConfigurer

@Configuration public class WebMvcConfig implements WebMvcConfigurer {      @Override     public void addCorsMappings(CorsRegistry registry) {         registry.addMapping("/hello");     } }

再次访问将会返回正常数据。

除了以上的配置外,还可以做更细致的限制

比如对请求的headers,请求的方法POST/GET...。请求的源进行限制。

@Slf4j @RestController public class Web1Controller {      @CrossOrigin     @RequestMapping("/hello")     public String hello(){         log.info("hello ");         return "hello," + new Date().toString();     } }

注解可以用在类上,也可以用在方法上,但必须是控制器类

配置和上面一样,也是可以对方法,header,源进行个性化限制。

@Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface CrossOrigin {     /** @deprecated */     @Deprecated     String[] DEFAULT_ORIGINS = new String[]{"*"};     /** @deprecated */     @Deprecated     String[] DEFAULT_ALLOWED_HEADERS = new String[]{"*"};     /** @deprecated */     @Deprecated     boolean DEFAULT_ALLOW_CREDENTIALS = false;     /** @deprecated */     @Deprecated     long DEFAULT_MAX_AGE = 1800L;      @AliasFor("origins")     String[] value() default {};      @AliasFor("value")     String[] origins() default {};      String[] allowedHeaders() default {};      String[] exposedHeaders() default {};      RequestMethod[] methods() default {};      String allowCredentials() default "";      long maxAge() default -1L; }

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!