乐闻世界logo
搜索文章和话题

How can you enable cross-origin resource sharing ( CORS ) in a Spring Boot application?

1 个月前提问
1 个月前修改
浏览次数11

1个答案

1

在Spring Boot应用程序中启用跨源资源共享(CORS)可以通过几种不同的方法实现,这取决于你的需求和配置的复杂性。下面我将介绍三种常见的方法来启用CORS。

方法1:使用@CrossOrigin注解

最简单的方法是在你的控制器或者具体的方法上使用@CrossOrigin注解。这种方法适用于简单场景,比如你只需要允许来自某个特定源的访问。

例子

java
import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController @CrossOrigin(origins = "http://example.com") public class MyController { @GetMapping("/data") public String getData() { return "Data from Spring Boot"; } }

在上述例子中,@CrossOrigin(origins = "http://example.com") 表示只有来自 http://example.com 的请求可以访问这个/data端点。

方法2:全局CORS配置

如果你需要为多个控制器或者整个应用程序设置CORS,可以通过在Spring Boot的配置类中使用WebMvcConfigurer来设置全局CORS配置。

例子

java
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; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://example.com") .allowedMethods("GET", "POST", "PUT", "DELETE") .allowedHeaders("*") .allowCredentials(true); } }

这段代码中,addCorsMappings方法添加了一个映射/**,这意味着所有的端点都将允许来自http://example.com的跨源请求,并且支持GET, POST, PUT, DELETE方法。

方法3:使用Spring Security

如果你的应用程序中已经集成了Spring Security,你可以在Spring Security的配置中加入CORS设置。

例子

java
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and() // 启用CORS .csrf().disable() .authorizeRequests() .antMatchers("/public/**").permitAll() .anyRequest().authenticated(); } }

在这个配置中,http.cors().and()启用了CORS,后续的配置确保了应用的安全性。

通过这些方法,你可以根据具体需求选择合适的方式来在Spring Boot应用程序中启用CORS。每种方法都有其适用场景和优势。

2024年8月7日 22:09 回复

你的答案