一文搞懂Spring Boot处理跨域请求

文章目录

  • 一、 什么是跨域请求?
  • 二、局部配置CORS
  • 三、全局配置CORS
  • 四、CORS 过滤器

一、 什么是跨域请求?

跨域请求(Cross-Origin Request)是指在浏览器中,一个网页的 JavaScript 代码尝试向与当前网页不同源(Origin)的服务器发起 HTTP 请求。这里的“源”由协议(Protocol)、域名(Domain)和端口(Port)三部分组成。如果这三个部分中有任何一个不同,就被认为是跨域请求。

一般我们遇到的跨域请求发生在前端服务器向后端服务器发送请求,前端和后端的端口号不同,产生了跨域问题

跨域请求的起因是浏览器的同源策略。同源策略是一种安全机制,它限制了从一个源加载的文档或脚本如何与另一个源的资源进行交互。同源策略的目的是防止恶意网站通过脚本访问其他网站的数据,从而保护用户隐私和安全。

思考

既然跨域问题是浏览器产生的,浏览器都不让发生跨域的请求,请求都发不出去,在后端设置那些跨域策略又为什么会起作用呢,为什么不去解决浏览器而是在后端解决跨域问题?

对于 ​跨域 的请求,浏览器会先发送一个 ​预检请求(Preflight Request)​,询问服务器是否允许跨域访问。如果服务器没有明确允许跨域,浏览器会阻止跨域请求,并返回错误(如 CORS policy 错误)。

​CORS(跨域资源共享,Cross-Origin Resource Sharing)

二、局部配置CORS

@RestController
@RequestMapping("/api")
//@CrossOrigin(origins = "https://example.com")
public class MyController {

    @CrossOrigin(origins = "https://example.com") // 允许指定源跨域访问,也可以加在MyController上
    @GetMapping("/data")
    public String getData() {
        return "Hello, CORS!";
    }
}

三、全局配置CORS

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 CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**") // 匹配的路径
                .allowedOrigins("https://example.com") // 允许的源
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的 HTTP 方法
                .allowedHeaders("*") // 允许的请求头
                .allowCredentials(true) // 是否允许携带凭证(如 Cookie)
                .maxAge(3600); // 预检请求的缓存时间
    }
}

四、CORS 过滤器

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsFilterConfig {

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(List.of("https://example.com")); // 允许的源
        config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE")); // 允许的 HTTP 方法
        config.setAllowedHeaders(List.of("*")); // 允许的请求头
        config.setAllowCredentials(true); // 是否允许携带凭证
        config.setMaxAge(3600L); // 预检请求的缓存时间
        source.registerCorsConfiguration("/**", config); // 注册到所有路径
        return new CorsFilter(source);
    }
}

你可能感兴趣的:(spring,boot,后端,java)