SpringBoot 实现跨域请求

本文介绍如何在SpringBoot和Nginx中配置跨域访问,并简要提及浏览器端的跨域设置。

跨域访问支持(Spring Boot、Nginx、浏览器)


一、Spring Boot跨域配置

我们的后端使用Spring Boot。Spring Boot跨域非常简单,只需书写以下代码即可。

@Configuration
public class CustomCORSConfiguration {
  private CorsConfiguration buildConfig() {
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    corsConfiguration.addAllowedOrigin("*");
    corsConfiguration.addAllowedHeader("*");
    corsConfiguration.addAllowedMethod("*");
    return corsConfiguration;
  }
  @Bean
  public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", buildConfig());
    return new CorsFilter(source);
  }
}

代码非常简单,不做赘述。该代码在Spring Boot 1.5.4中测试通过。

二、Nginx跨域配置

某天,我们将Spring Boot应用用Nginx反向代理。而前端跨域请求的需求不减,于是乎。

Nginx跨域也比较简单,只需添加以下配置即可。

location / {
	proxy_pass http://localhost:8080;
	if ($request_method = 'OPTIONS') {
		add_header 'Access-Control-Allow-Origin' '*';
		add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
		add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Token';
		add_header 'Access-Control-Max-Age' 1728000;
		add_header 'Content-Type' 'text/plain; charset=utf-8';
		add_header 'Content-Length' 0;
		return 204;
	}
	if ($request_method = 'POST') {
		add_header 'Access-Control-Allow-Origin' '*';
		add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
		add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Token';
		add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Token';
	}
	if ($request_method = 'GET') {
		add_header 'Access-Control-Allow-Origin' '*';
		add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
		add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Token';
		add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Token';
	}
}

其中:add_header 'Access-Control-Expose-Headers' 务必加上你请求时所带的header。例如本例中的“Token”,其实是前端传给后端过来的。如果记不得也没有关系,浏览器的调试器会有详细说明。

参考文档:https://enable-cors.org/server_nginx.html

B.T.W,阿里云中文档描述到Nginx也可通过crossdomain.xml配置文件跨域:https://helpcdn.aliyun.com/knowledge_detail/41123.html ,不过笔者并未采用这种方式。

三、浏览器设置跨域

Chrome、Firefox本身是可以通过配置支持跨域请求的。

:通过浏览器设置实现跨域的玩法,个人没有亲测过。


转载自:http://www.itmuch.com/work/cors/


在 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 的方式。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值