Spring Boot中的跨域资源共享(CORS)处理

Spring Boot中的跨域资源共享(CORS)处理

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

在Web应用开发中,跨域资源共享(CORS)是一个常见的问题。当一个Web应用需要与另一个域下的Web服务进行交互时,浏览器出于安全考虑,会默认阻止这种跨域请求。Spring Boot作为目前流行的Java Web应用开发框架,提供了多种方式来处理CORS问题。

CORS 基本概念

CORS是一个W3C标准,全称是"Cross-Origin Resource Sharing"。它允许Web应用在遵守同源策略的前提下,安全地访问跨域资源。

Spring Boot 中的 CORS 处理

Spring Boot提供了几种方式来处理CORS,包括使用注解、配置类和全局配置。

使用 @CrossOrigin 注解

在Spring Boot中,可以通过@CrossOrigin注解来允许特定源的跨域请求。这个注解可以应用于类或方法上。

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

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

    @GetMapping("/api/data")
    public String getData() {
        return "Data from server";
    }
}

使用 WebMvcConfigurer 配置 CORS

通过实现WebMvcConfigurer接口,可以在Spring Boot中自定义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 WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("http://example.com")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}

全局 CORS 配置

Spring Boot 2.2 版本开始,提供了一种更简单的全局CORS配置方式。

# application.properties
spring.web.cors.allow-credentials=true
spring.web.cors.allowed-origins=http://example.com
spring.web.cors.allowed-methods=GET,POST,PUT,DELETE
spring.web.cors.allowed-headers=*

使用 HttpSecurity 配置 CORS

在Spring Security中,也可以通过配置HttpSecurity来处理CORS。

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()
            // 其他配置...
            .csrf().disable();
    }
}

自定义 CORS 过滤器

如果需要更复杂的CORS处理逻辑,可以自定义一个CORS过滤器。

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CustomCorsFilter 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://example.com");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN");
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }
}

CORS 预请求

浏览器在发送实际的跨域请求之前,会先发送一个预请求(OPTIONS请求),以确认服务器是否允许跨域请求。Spring Boot可以通过配置来简化这个过程。

CORS 与 Spring Security 结合使用

在使用Spring Security的情况下,CORS的处理需要与Spring Security的配置结合。

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfigurationSource;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final CorsConfigurationSource corsConfigurationSource;

    public SecurityConfig(CorsConfigurationSource corsConfigurationSource) {
        this.corsConfigurationSource = corsConfigurationSource;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()
            // 其他配置...
            .csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 认证管理器配置...
    }
}

CORS 与 Zuul 结合使用

在使用Zuul作为API网关时,CORS的处理可以在Zuul中进行。

zuul:
  routes:
    myService:
      path: /myService/**
      serviceId: my-service
  cors:
    allowed-origins: "*"
    allowed-methods: GET,POST,PUT,DELETE
    allowed-headers: "*"
    expose-headers: "*"

CORS 与 Spring Cloud Gateway 结合使用

在使用Spring Cloud Gateway时,可以通过全局过滤器来处理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 GatewayConfig {

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

总结

本文介绍了Spring Boot中处理CORS的多种方法,包括使用注解、配置类、全局配置、自定义过滤器以及与Spring Security、Zuul和Spring Cloud Gateway的结合使用。通过这些方法,开发者可以根据实际需求灵活地处理跨域问题,提高Web应用的安全性和可用性。

本文著作权归聚娃科技微赚淘客系统开发者团队,转载请注明出处!

posted @ 2024-08-15 21:48  省赚客开发者团队  阅读(1)  评论(0编辑  收藏  举报