• 利用CORS解决前后端分离的跨域资源问题


    CORS 即CrossOrigin Resources Sharing-跨域资源共享,它定义了一种浏览器和服务器交互的方式来确定是否允许跨域请求。它是一个妥协,有更大的灵活性,但比起简单地允许所有这些的要求来说更加安全。简言之,CORS就是为了让AJAX可以实现可控的跨域访问而生的。

    注意 CORS也具有一定的风险性,比如请求中只能说明来自于一个特定的域但不能验证是否可信,而且也容易被第三方入侵。


    实现CORS的几种方式

    • 通过自定义Filter
    public class CorsFilter implements Filter {
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
            httpServletResponse.setHeader("Access-Control-Allow-Headers",
                    "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");// 允许cookie
            chain.doFilter(request, response);
        }
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
        }
        @Override
        public void destroy() {
        }
    }
    
    <!-- CORS过滤器,需要确保CorsFilter的顺序先于其他的filters start -->
    <filter>
        <filter-name>corsFilter</filter-name>
        <filter-class>com.springmvc.filter.CorsFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>corsFilter</filter-name>
        <url-pattern>*.do</url-pattern>
    </filter-mapping>
    <!-- CORS过滤器 end -->
    
    • Spring3, Maven工程直接引用第三方依赖
    <dependency>
        <groupId>com.thetransactioncompany</groupId>
        <artifactId>cors-filter</artifactId>
        <version>[ version ]</version>
    </dependency>
    
    <filter>  
        <filter-name>CORS</filter-name>  
        <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>  
        <init-param>  
            <param-name>cors.allowOrigin</param-name> 
            <param-value>*</param-value> 
        </init-param>  
        <init-param>  
            <param-name>cors.supportedMethods</param-name> 
            <param-value>GET, POST, HEAD, PUT, DELETE</param-value> 
        </init-param>  
        <init-param>  
            <param-name>cors.supportedHeaders</param-name> 
            <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value> 
        </init-param>  
        <init-param>  
            <param-name>cors.exposedHeaders</param-name> 
            <param-value>Set-Cookie</param-value> 
        </init-param>  
        <init-param>  
            <param-name>cors.supportsCredentials</param-name> 
            <param-value>true</param-value> 
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>CORS</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>
    
    • Spring 4.2以上

    由于Spring 4.2版本开始,不需要引用第三方依赖:
    在Spring MVC 中增加CORS支持非常简单,可以配置全局的规则,也可以使用@CrossOrigin注解进行细粒度的配置。

    1.全局配置

    配置在spring.xml文件中:

    <!-- 允许所有的origins -->
    <mvc:cors>
        <mvc:mapping path="/**" />
    </mvc:cors>
    <!-- 控制具体的访问路径和允许的域名 -->
    <mvc:cors>
        <mvc:mapping path="/api/**"
            allowed-origins="http://domain1.com, http://domain2.com"
            allowed-methods="GET, PUT"
            allowed-headers="header1, header2, header3"
            exposed-headers="header1, header2" allow-credentials="false"
            max-age="123" />
    
        <mvc:mapping path="/resources/**"
            allowed-origins="http://domain1.com" />
    </mvc:cors>
    

    2.注解

    可以作用在controller级别和method级别:

    @CrossOrigin(origins = {"http://localhost:8585"}, maxAge = 4800, allowCredentials = "false")
    @RestController
    @RequestMapping("info")
    public class PersonController {
    	@Autowired
    	private PersonService service;
    	@CrossOrigin(origins = {"http://localhost:8787"}, maxAge = 6000)
    	@RequestMapping("home")
    	public List<Person> showData() {
    		List<Person> list = service.getAllPerson();
    		return list;
     	}
    	@RequestMapping("nexthome")
    	public List<Person> showDataNext() {
    		List<Person> list = service.getAllPerson();
    		return list;
     	}
    } 
    
    • SpringBoot
    @Configuration
    @EnableWebMvc
    public class AppConfig extends WebMvcConfigurerAdapter {
    	@Override
    	public void addCorsMappings(CorsRegistry registry) {
    	  registry.addMapping("/info/**")
    	   	  .allowedOrigins("http://localhost:8585", "http://localhost:8787")
    		  .allowedMethods("POST", "GET",  "PUT", "OPTIONS", "DELETE")
    		  .allowedHeaders("X-Auth-Token", "Content-Type")
    		  .exposedHeaders("custom-header1", "custom-header2")
    		  .allowCredentials(false)
    		  .maxAge(4800);
    	}
    } 
    

    感谢阅读这份文档,希望有帮忙到您。

  • 相关阅读:
    Python快速入门魔力手册PDF高清完整版百度云盘免费下载|零基础学习python入门教程
    Python语言及其应用PDF高清完整版百度云盘免费下载|python基础教程PDF电子书推荐
    Python游戏编程快速上手(第四版)PDF高清完整版百度云盘免费下载|零基础入门学pythonPDF教程
    python学习手册(第4版)PDF高清完整版百度云盘免费下载|零基础学习python入门指导推荐教材
    超全的HTTP请求响应码详细解析
    Python袖珍指南第5版PDF高清完整版百度云盘免费下载|python基础教程菜鸟教程
    Python趣味编程:从入门到人工智能PDF高清完整版百度云盘免费下载|python3零基础入门学习教程
    Python程序设计(第3版)PDF高清完整版百度云盘免费下载|python基础编程入门学习教程
    Python编程初学者指南PDF高清完整版百度云盘免费下载|python基础教程电子书
    hadoop常见面试题
  • 原文地址:https://www.cnblogs.com/yinxiang/p/8908564.html
Copyright © 2020-2023  润新知