首页 > 其他分享 >Spring Boot中的跨域资源共享(CORS)处理

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

时间:2024-08-15 21:49:11浏览次数:7  
标签:web 跨域 Spring CORS Boot springframework org import

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应用的安全性和可用性。

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

标签:web,跨域,Spring,CORS,Boot,springframework,org,import
From: https://www.cnblogs.com/szk123456/p/18361861

相关文章

  • Spring Boot集成Zuul API网关
    SpringBoot集成ZuulAPI网关大家好,我是微赚淘客返利系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!在微服务架构中,API网关是一个不可或缺的组件,它负责请求的路由、负载均衡、认证、监控等任务。Zuul是一个高性能的API网关服务,由Netflix开源。SpringBoot集成Zuul可以快速......
  • [Spring]springboot
    简单介绍一下Spring?有啥缺点?Spring是重量级企业开发框架EnterpriseJavaBean(EJB)的替代品,Spring为企业级Java开发提供了一种相对简单的方法,通过依赖注入和面向切面编程,用简单的Java对象(PlainOldJavaObject,POJO)实现了EJB的功能虽然Spring的组件代码是轻量......
  • SpringBoot统一异常处理
    简介在SpringBoot项目中实现统一的异常处理是一种常见的做法,这有助于保持代码的整洁并提供一致的错误响应格式。SpringBoot中的统一异常处理是一种机制,用于集中管理和格式化应用程序中抛出的所有异常。这种机制可以提高程序的健壮性和用户体验,同时简化开发过程。统一异常处理......
  • 基于Spring AOP与Redisson的令牌桶限流注解实践
    1.什么是限流举个例子......
  • 全面掌握 Spring Cloud LoadBalancer:从自定义到策略优化的实战教程
    引言在微服务架构中,负载均衡是保障系统高效运行的关键技术之一。无论是服务端负载均衡还是客户端负载均衡,合理的负载均衡策略都能显著提升系统的稳定性和响应速度。本文将从基础概念入手,详细讲解如何在SpringCloud中实现和优化负载均衡,并结合实际案例,帮助读者快速上手并......
  • 【Springboot系统开发】——网上商城购物系统(文末附源码)源码+万字文档+配套PPT
    ......
  • 003springboot图书个性化推荐系统的设计与实现———源码+数据库文件+万字文档+配套PP
     博主介绍:java高级开发,从事互联网行业六年,熟悉各种主流语言,精通java、python、php、爬虫、web开发,已经做了六年的毕业设计程序开发,开发过上千套毕业设计程序,没有什么华丽的语言,只有实实在在的写点程序。......
  • Spring Boot集成Spring Cloud Config实现配置中心
    SpringBoot集成SpringCloudConfig实现配置中心大家好,我是微赚淘客返利系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!随着微服务架构的流行,集中管理配置信息变得越来越重要。SpringCloudConfig提供了一个配置服务器,用于集中管理分布式系统中的配置信息。本文将介绍如......
  • Spring Boot中的服务降级与熔断机制
    SpringBoot中的服务降级与熔断机制大家好,我是微赚淘客返利系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!在微服务架构中,服务降级和熔断是保证系统稳定性的重要机制。服务降级是指在系统负载过高或不稳定时,暂时关闭或简化一些功能,以保证核心业务的正常运行。熔断则是一种......
  • Spring Boot应用的数据库连接池管理
    SpringBoot应用的数据库连接池管理大家好,我是微赚淘客返利系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!数据库连接池是SpringBoot应用与数据库交互的重要组成部分,它帮助应用管理数据库连接,提高资源利用率和系统性能。SpringBoot内置了对多种数据库连接池的支持,包括Hik......