SpringBoot设置跨域请求

本文介绍了现代浏览器中的跨域问题及解决方案,包括JSONP、代理机制和CORS协议,并提供了配置示例。

现代浏览器处于安全的考虑,在http/https请求时必须遵守同源策略,否则即使跨域的http/https 请求,默认情况下是被禁止的,ip(域名)不同、或者端口不同、协议不同(比如http、https) 都会造成跨域问题。

一、 前端解决方案 
1. 使用 JSONP 来支持跨域的请求,JSONP 实现跨域请求的原理简单的说,就是动态创建 
script 标签,然后利用 script 的 SRC 不受同源策略约束来跨域获取数据。缺点是需 
要后端配合输出特定的返回信息。 
2. 利用反应代理的机制来解决跨域的问题,前端请求的时候先将请求发送到同源地址的后 
端,通过后端请求转发来避免跨域的访问。

后来 HTML5 支持了 CORS 协议。CORS 是一个 W3C 标准,全称是”跨域资源共享”(Cross-origin resource sharing),允许浏览器向跨源服务器,发出 XMLHttpRequest 请求,从而克服了 AJAX 只能同源使用的限制。它通过服务器增加一个特殊的 Header[Access-Control-Allow-Origin]来告诉客户端跨域的限制,如果浏览器支持 CORS、并且判断 Origin 通过的话,就会允许 XMLHttpRequest 发起跨域请求。

三种配置方式:

  1. 配置 过滤器
    @Configuration
    public class GlobalCorsConfig {
        @Bean
        public CorsFilter corsFilter() {
            CorsConfiguration config = new CorsConfiguration();
              config.addAllowedOrigin("*");
              config.setAllowCredentials(true);
              config.addAllowedMethod("*");
              config.addAllowedHeader("*");
              config.addExposedHeader("*");
    
            UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
            configSource.registerCorsConfiguration("/**", config);
    
            return new CorsFilter(configSource);
        }
    }

     

  2. 配置拦截器
    @Configuration
    public class MyConfiguration extends WebMvcConfigurerAdapter  {
    
        @Override  
        public void addCorsMappings(CorsRegistry registry) {  
            registry.addMapping("/**")  
                    .allowCredentials(true)  
                    .allowedHeaders("*")  
                    .allowedOrigins("*")  
                    .allowedMethods("*");  
    
        }  
    }
    

     

  3. 单个请求
    @RequestMapping("/hello")
    @CrossOrigin("http://localhost:8080") 
    public String hello( ){
    return "Hello World";
    }

     

在 Spring Boot 应用中处理请求(CORS)可以通过多种方式进行配置,以确保客户端能够安全地进行访问。以下是几种常见的配置方法: ### 1. 使用 `@CrossOrigin` 注解 对于单个控制器或方法,可以使用 `@CrossOrigin` 注解来启用 CORS 支持。该注解可以设置允许的来源、方法、头部等属性。 ```java @RestController @RequestMapping("/api") @CrossOrigin(origins = "http://www.example.com", methods = {RequestMethod.GET, RequestMethod.POST}) public class MyController { // 控制器方法 } ``` 此方法适用于简单的场景,但不适合全局配置[^1]。 --- ### 2. 全局配置:实现 `WebMvcConfigurer` 接口 为了在整个应用中统一处理 CORS 请求,可以通过实现 `WebMvcConfigurer` 接口并重写 `addCorsMappings` 方法来进行全局配置。 ```java @Configuration @EnableWebMvc public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("http://www.example.com") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("Content-Type", "Authorization") .exposedHeaders("X-Custom-Header") .maxAge(3600) .allowCredentials(true); } } ``` 上述代码示例中,`allowedOrigins` 设置了允许请求的源,`allowedMethods` 指定了允许的方法,`allowedHeaders` 设置了允许的头部信息,`maxAge` 定义了预检请求的结果能被缓存的时间(单位为秒),而 `allowCredentials` 则决定是否允许携带凭证(如 cookies)。 --- ### 3. 自定义过滤器:实现 `Filter` 接口 另一种灵活的方式是通过自定义过滤器来处理 CORS 请求。这种方式提供了更细粒度的控制,并且可以在请求进入 Spring MVC 框架之前就进行处理。 ```java @Component public class CorsFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest request = (HttpServletRequest) req; response.setHeader("Access-Control-Allow-Origin", "http://www.example.com"); response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization"); response.setHeader("Access-Control-Expose-Headers", "X-Custom-Header"); response.setHeader("Access-Control-Allow-Credentials", "true"); if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { response.setStatus(HttpServletResponse.SC_OK); } else { chain.doFilter(req, res); } } } ``` 这种方法适用于需要更复杂逻辑的场景,例如动态设置允许的源或者根据请求头进行判断[^1]。 --- ### 4. 配置 `application.properties` 或 `application.yml` 虽然 Spring Boot 并不直接支持在 `application.properties` 或 `application.yml` 文件中配置 CORS 参数,但可以通过编写自定义属性类并与 `@CrossOrigin` 或 `WebMvcConfigurer` 结合使用来实现类似效果。 例如,在 `application.yml` 中定义: ```yaml cors: allowed-origins: http://www.example.com allowed-methods: GET,POST,PUT,DELETE,OPTIONS max-age: 3600 allow-credentials: true ``` 然后创建一个配置类读取这些属性,并应用到全局 CORS 配置中。 --- ### 5. 使用 Spring Security 的 CORS 支持 如果你的应用集成了 Spring Security,还可以通过其内置的 CORS 支持来处理请求。这通常与 `WebMvcConfigurer` 配合使用,以确保安全性策略也被正确应用。 ```java @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and() .csrf().disable(); } @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Arrays.asList("http://www.example.com")); configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); configuration.setAllowedHeaders(Arrays.asList("Content-Type", "Authorization")); configuration.setExposedHeaders(Arrays.asList("X-Custom-Header")); configuration.setMaxAge(3600L); configuration.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/api/**", configuration); return source; } } ``` 这种方式特别适合那些已经启用了 Spring Security 的项目,它可以更好地整合安全性和访问控制。 --- ### 总结 以上方法各有优劣,选择哪种方式取决于具体需求和项目的复杂程度。对于大多数中小型项目,推荐使用 `WebMvcConfigurer` 实现全局配置;而对于需要更高灵活性或集成安全框架的情况,则可以选择自定义过滤器或结合 Spring Security 的方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值