springboot解决CORS跨域的方式有哪些

发布时间:2022-07-01 13:51:42 作者:iii
来源:亿速云 阅读:361

SpringBoot解决CORS跨域的方式有哪些

1. 引言

在现代Web开发中,前后端分离的架构越来越普遍。前端应用通常运行在一个域名下,而后端API服务则运行在另一个域名下。这种架构带来了跨域资源共享(CORS,Cross-Origin Resource Sharing)的问题。CORS是一种机制,允许浏览器向不同域名的服务器发起请求,从而解决跨域问题。

Spring Boot流行的Java后端框架,提供了多种方式来解决CORS问题。本文将详细介绍这些方法,并通过代码示例展示如何在实际项目中应用这些解决方案。

2. CORS简介

2.1 什么是CORS?

CORS(Cross-Origin Resource Sharing)是一种机制,允许浏览器向不同域名的服务器发起请求。在默认情况下,浏览器会阻止跨域请求,以防止恶意网站窃取用户数据。CORS通过HTTP头来告诉浏览器,哪些跨域请求是被允许的。

2.2 CORS的工作原理

当一个浏览器发起跨域请求时,它会先发送一个预检请求(Preflight Request),询问服务器是否允许该跨域请求。服务器通过响应头来告诉浏览器是否允许该请求。如果服务器允许,浏览器才会发送实际的请求。

2.3 CORS的常见问题

在实际开发中,CORS问题常常表现为以下几种情况:

3. Spring Boot中解决CORS的方式

Spring Boot提供了多种方式来解决CORS问题。下面我们将详细介绍这些方法。

3.1 使用@CrossOrigin注解

@CrossOrigin注解是Spring Boot中最简单的解决CORS问题的方式。它可以应用于控制器类或方法上,允许特定的跨域请求。

3.1.1 在控制器类上使用@CrossOrigin

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

    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }
}

在上面的代码中,@CrossOrigin注解允许来自http://example.com的跨域请求访问/hello路径。

3.1.2 在方法上使用@CrossOrigin

@RestController
public class MyController {

    @GetMapping("/hello")
    @CrossOrigin(origins = "http://example.com")
    public String hello() {
        return "Hello, World!";
    }
}

在这个例子中,@CrossOrigin注解只允许来自http://example.com的跨域请求访问/hello路径。

3.1.3 配置多个允许的源

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

    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }
}

在这个例子中,@CrossOrigin注解允许来自http://example.comhttp://another-example.com的跨域请求访问/hello路径。

3.2 使用CorsRegistry配置全局CORS

CorsRegistry是Spring Boot中配置全局CORS的一种方式。通过WebMvcConfigurer接口,我们可以在应用启动时配置全局的CORS策略。

3.2.1 配置全局CORS

@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)
                .maxAge(3600);
    }
}

在这个例子中,我们配置了全局的CORS策略,允许来自http://example.com的跨域请求访问/api/**路径下的所有资源。允许的HTTP方法包括GETPOSTPUTDELETE,允许所有请求头,允许携带凭证(如Cookies),并且预检请求的缓存时间为3600秒。

3.2.2 配置多个允许的源

@Configuration
public class WebConfig implements WebMvcConfigurer {

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

在这个例子中,我们配置了全局的CORS策略,允许来自http://example.comhttp://another-example.com的跨域请求访问/api/**路径下的所有资源。

3.3 使用CorsFilter配置CORS

CorsFilter是Spring Boot中另一种配置CORS的方式。通过自定义CorsFilter,我们可以更灵活地控制CORS策略。

3.3.1 配置CorsFilter

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

在这个例子中,我们配置了一个CorsFilter,允许来自http://example.com的跨域请求访问/api/**路径下的所有资源。允许所有HTTP方法和请求头,并且允许携带凭证。

3.3.2 配置多个允许的源

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

在这个例子中,我们配置了一个CorsFilter,允许来自http://example.comhttp://another-example.com的跨域请求访问/api/**路径下的所有资源。

3.4 使用CorsConfigurationSource配置CORS

CorsConfigurationSource是Spring Boot中配置CORS的另一种方式。通过实现CorsConfigurationSource接口,我们可以自定义CORS策略。

3.4.1 配置CorsConfigurationSource

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowCredentials(true);
    configuration.addAllowedOrigin("http://example.com");
    configuration.addAllowedMethod("*");
    configuration.addAllowedHeader("*");
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/api/**", configuration);
    return source;
}

在这个例子中,我们配置了一个CorsConfigurationSource,允许来自http://example.com的跨域请求访问/api/**路径下的所有资源。允许所有HTTP方法和请求头,并且允许携带凭证。

3.4.2 配置多个允许的源

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowCredentials(true);
    configuration.addAllowedOrigin("http://example.com");
    configuration.addAllowedOrigin("http://another-example.com");
    configuration.addAllowedMethod("*");
    configuration.addAllowedHeader("*");
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/api/**", configuration);
    return source;
}

在这个例子中,我们配置了一个CorsConfigurationSource,允许来自http://example.comhttp://another-example.com的跨域请求访问/api/**路径下的所有资源。

3.5 使用WebFluxConfigurer配置CORS

在Spring WebFlux应用中,我们可以通过WebFluxConfigurer接口来配置CORS策略。

3.5.1 配置全局CORS

@Configuration
public class WebFluxConfig implements WebFluxConfigurer {

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

在这个例子中,我们配置了全局的CORS策略,允许来自http://example.com的跨域请求访问/api/**路径下的所有资源。允许的HTTP方法包括GETPOSTPUTDELETE,允许所有请求头,允许携带凭证,并且预检请求的缓存时间为3600秒。

3.5.2 配置多个允许的源

@Configuration
public class WebFluxConfig implements WebFluxConfigurer {

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

在这个例子中,我们配置了全局的CORS策略,允许来自http://example.comhttp://another-example.com的跨域请求访问/api/**路径下的所有资源。

3.6 使用CorsWebFilter配置CORS

在Spring WebFlux应用中,我们还可以通过CorsWebFilter来配置CORS策略。

3.6.1 配置CorsWebFilter

@Bean
public CorsWebFilter corsWebFilter() {
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("http://example.com");
    config.addAllowedMethod("*");
    config.addAllowedHeader("*");
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/api/**", config);
    return new CorsWebFilter(source);
}

在这个例子中,我们配置了一个CorsWebFilter,允许来自http://example.com的跨域请求访问/api/**路径下的所有资源。允许所有HTTP方法和请求头,并且允许携带凭证。

3.6.2 配置多个允许的源

@Bean
public CorsWebFilter corsWebFilter() {
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("http://example.com");
    config.addAllowedOrigin("http://another-example.com");
    config.addAllowedMethod("*");
    config.addAllowedHeader("*");
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/api/**", config);
    return new CorsWebFilter(source);
}

在这个例子中,我们配置了一个CorsWebFilter,允许来自http://example.comhttp://another-example.com的跨域请求访问/api/**路径下的所有资源。

3.7 使用@CrossOriginCorsRegistry结合

在实际开发中,我们可能会同时使用@CrossOrigin注解和CorsRegistry来配置CORS策略。这种情况下,CorsRegistry的配置会覆盖@CrossOrigin注解的配置。

3.7.1 结合使用@CrossOriginCorsRegistry

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

    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }
}

@Configuration
public class WebConfig implements WebMvcConfigurer {

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

在这个例子中,@CrossOrigin注解允许来自http://example.com的跨域请求访问/hello路径,而CorsRegistry配置允许来自http://another-example.com的跨域请求访问/api/**路径下的所有资源。

3.8 使用CorsFilterCorsRegistry结合

在实际开发中,我们可能会同时使用CorsFilterCorsRegistry来配置CORS策略。这种情况下,CorsFilter的配置会覆盖CorsRegistry的配置。

3.8.1 结合使用CorsFilterCorsRegistry

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

@Configuration
public class WebConfig implements WebMvcConfigurer {

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

在这个例子中,CorsFilter配置允许来自http://example.com的跨域请求访问/api/**路径下的所有资源,而CorsRegistry配置允许来自http://another-example.com的跨域请求访问/api/**路径下的所有资源。

3.9 使用CorsConfigurationSourceCorsRegistry结合

在实际开发中,我们可能会同时使用CorsConfigurationSourceCorsRegistry来配置CORS策略。这种情况下,CorsConfigurationSource的配置会覆盖CorsRegistry的配置。

3.9.1 结合使用CorsConfigurationSourceCorsRegistry

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowCredentials(true);
    configuration.addAllowedOrigin("http://example.com");
    configuration.addAllowedMethod("*");
    configuration.addAllowedHeader("*");
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/api/**", configuration);
    return source;
}

@Configuration
public class WebConfig implements WebMvcConfigurer {

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

在这个例子中,CorsConfigurationSource配置允许来自http://example.com的跨域请求访问/api/**路径下的所有资源,而CorsRegistry配置允许来自http://another-example.com的跨域请求访问/api/**路径下的所有资源。

3.10 使用CorsWebFilterWebFluxConfigurer结合

在Spring WebFlux应用中,我们可能会同时使用CorsWebFilterWebFluxConfigurer来配置CORS策略。这种情况下,CorsWebFilter的配置会覆盖WebFluxConfigurer的配置。

3.10.1 结合使用CorsWebFilterWebFluxConfigurer

@Bean
public CorsWebFilter corsWebFilter() {
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("http://example.com");
    config.addAllowedMethod("*");
    config.addAllowedHeader("*");
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/api/**", config);
    return new CorsWebFilter(source);
}

@Configuration
public class WebFluxConfig implements WebFluxConfigurer {

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

在这个例子中,CorsWebFilter配置允许来自http://example.com的跨域请求访问/api/**路径下的所有资源,而WebFluxConfigurer配置允许来自http://another-example.com的跨域请求访问/api/**路径下的所有资源。

4. 总结

在Spring Boot中,我们可以通过多种方式来解决CORS问题。每种方式都有其适用的场景和优缺点。在实际开发中,我们可以根据项目的需求选择合适的CORS解决方案。

推荐阅读:
  1. 跨域CORS
  2. Springboot如何处理CORS跨域请求

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot cors

上一篇:Java中super关键字怎么使用

下一篇:Vue怎么实现前端页面缓存

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》