点击关注公众号,更多资讯及时推送↓
域资源共享(CORS,Cross-Origin Resource Sharing)是一个浏览器安全特性,它允许网页从一个域请求到另一个域的资源。在开发基于微服务的应用程序时,跨域请求是一个常见的问题。本文将详细介绍几种在Spring Boot 3中解决跨域问题的方法,并提供相应的代码示例。

1. 什么是跨域

跨域问题出现在浏览器试图访问不同源(域、协议、端口)的资源时。为了安全,浏览器默认阻止这种访问。这种限制对前后端分离开发造成了一定的困扰,因此需要通过某些方式来允许跨域请求。

2. Spring Boot 3解决跨域问题的方法概述

Spring Boot提供了多种方法来解决跨域问题,主要包括:
  • 使用@CrossOrigin注解
  • 全局配置跨域
  • 使用过滤器(Filter)
  • 使用CORS配置类

3. 使用@CrossOrigin注解解决跨域问题

@CrossOrigin注解可以直接在控制器或者方法上使用,允许特定的域名访问。

示例代码

@RestController@RequestMapping("/api")public class ExampleController {    @CrossOrigin(origins = "http://example.com")    @GetMapping("/greeting")    public ResponseEntity<String> greeting() {        return ResponseEntity.ok("Hello, World!");    }}
上述代码允许http://example.com域名访问/api/greeting接口。

4. 全局配置跨域

如果需要为所有控制器统一配置跨域,可以通过实现一个WebMvcConfigurer接口来达到目的。

示例代码

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;@Configurationpublic class WebConfig implements WebMvcConfigurer {    @Override    public void addCorsMappings(CorsRegistry registry) {        registry.addMapping("/**")                .allowedOrigins("http://example.com")                .allowedMethods("GET", "POST", "PUT", "DELETE")                .allowedHeaders("*")                .allowCredentials(true);    }}
此配置允许http://example.com域名通过GET、POST、PUT和DELETE方法访问所有路径。

5. 使用过滤器解决跨域问题

使用过滤器可以在Spring Security中配置跨域请求。这种方法适用于需要更复杂的安全配置场景。

示例代码

import org.springframework.context.annotation.Configuration;import org.springframework.web.filter.CorsFilter;import org.springframework.context.annotation.Bean;import org.springframework.core.Ordered;import org.springframework.core.annotation.Order;import org.springframework.web.cors.CorsConfiguration;import org.springframework.web.cors.UrlBasedCorsConfigurationSource;@Configurationpublic class CorsConfig {    @Bean    @Order(Ordered.HIGHEST_PRECEDENCE)    public CorsFilter corsFilter() {        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();        CorsConfiguration config = new CorsConfiguration();        config.setAllowCredentials(true);        config.addAllowedOrigin("http://example.com");        config.addAllowedHeader("*");        config.addAllowedMethod("*");        source.registerCorsConfiguration("/**", config);        return new CorsFilter(source);    }}
此配置允许http://example.com域名通过任意HTTP方法访问所有路径。

6. 使用CORS配置类解决跨域问题

Spring Security 5提供了一种新的跨域配置方法,可以在安全配置中直接定义CORS规则。

示例代码

import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.web.SecurityFilterChain;import org.springframework.web.cors.CorsConfiguration;import org.springframework.web.cors.UrlBasedCorsConfigurationSource;import org.springframework.web.filter.CorsFilter;@EnableWebSecurity@Configurationpublic class SecurityConfig {    @Bean    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {        http.cors().and().csrf().disable();        return http.build();    }    @Bean    public CorsFilter corsFilter() {        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();        CorsConfiguration config = new CorsConfiguration();        config.setAllowCredentials(true);        config.addAllowedOrigin("http://example.com");        config.addAllowedHeader("*");        config.addAllowedMethod("*");        source.registerCorsConfiguration("/**", config);        return new CorsFilter(source);    }}

在此配置中,我们首先禁用了CSRF保护(仅在确实需要时),然后配置了CORS过滤器。

7. 总结

在Spring Boot 3中,有多种方法可以解决跨域问题,包括使用@CrossOrigin注解、全局配置、过滤器和CORS配置类等。选择合适的方法取决于具体的需求和项目的复杂性。

获取方式:点“在看”,关注公众号并回复【Java、1024、AI、游戏领取,更多内容陆续奉上。
PS:因公众号平台更改了推送规则,如果不想错过内容,记得读完点一下在看,加个星标,这样每次新文章推送才会第一时间出现在你的订阅列表里。

“在看”支持码农呀,谢谢啦

本篇文章来源于微信公众号: 新生代码农



微信扫描下方的二维码阅读本文

此作者没有提供个人介绍
最后更新于 2024-08-02