使用Spring Boot实现跨域资源共享(CORS)

大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!

1. CORS概述

跨域资源共享(CORS)是一种机制,使用额外的HTTP头部来告诉浏览器允许运行在一个域上的Web应用访问来自不同源服务器上的指定资源。在现代Web应用中,由于安全策略的限制,经常需要处理跨域请求。

2. Spring Boot中配置CORS

在Spring Boot中,可以通过配置来实现CORS支持。下面是一个示例,展示了如何配置Spring Boot应用以允许特定的域访问资源。

package cn.juwatech.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:8080")  // 允许访问的源地址
                .allowedMethods("GET", "POST", "PUT", "DELETE")  // 允许的请求方法
                .allowedHeaders("*")  // 允许的请求头
                .allowCredentials(true)  // 是否支持发送Cookie
                .maxAge(3600);  // 预检请求的有效期,单位秒
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.

3. 示例代码说明

上述代码中,我们创建了一个WebConfig类,并实现了WebMvcConfigurer接口。在addCorsMappings方法中,配置了跨域请求的细节:

  • .addMapping("/**"):允许所有路径的请求。
  • .allowedOrigins("http://localhost:8080"):指定允许访问的源地址,这里是http://localhost:8080
  • .allowedMethods("GET", "POST", "PUT", "DELETE"):允许的HTTP请求方法。
  • .allowedHeaders("*"):允许的请求头。
  • .allowCredentials(true):是否允许发送Cookie。
  • .maxAge(3600):预检请求的有效期,单位秒。

4. 在Controller中使用CORS

除了全局配置外,还可以在具体的Controller类或方法上使用@CrossOrigin注解来配置CORS。

package cn.juwatech.controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://localhost:8080")
public class MyController {

    @GetMapping("/data")
    public String getData() {
        return "Data from API";
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

在上述示例中,@CrossOrigin(origins = "http://localhost:8080")指定了/api/data接口允许来自http://localhost:8080的跨域请求。

5. 配置细节说明

  • allowedOrigins:允许的源地址,可以配置多个。
  • allowedMethods:允许的HTTP方法,如GET、POST等。
  • allowedHeaders:允许的请求头,可以配置具体的头信息。
  • allowCredentials:是否支持发送Cookie。
  • maxAge:预检请求的有效期,避免浏览器频繁发送预检请求。

6. 总结

本文介绍了在Spring Boot中如何配置和使用CORS来处理跨域资源共享问题。通过配置全局的WebConfig类或使用@CrossOrigin注解,可以灵活地控制哪些域名和资源可以进行跨域访问,从而确保Web应用程序的安全性和可用性。