springboot设置允许跨域
时间: 2025-01-16 20:12:10 浏览: 36
### 配置CORS以允许跨域请求
在Spring Boot应用程序中,可以通过多种方式来配置CORS(跨源资源共享),以便处理来自不同域名的HTTP请求。
#### 使用`@CrossOrigin`注解
对于简单的场景,在控制器方法上使用`@CrossOrigin`注解是一种便捷的方式。这不需要额外的具体配置就能生效[^1]:
```java
@RestController
public class MyController {
@CrossOrigin(origins = "http://example.com")
@GetMapping("/hello")
public String hello() {
return "Hello World";
}
}
```
此代码片段展示了如何通过指定特定原点来限定哪些网站可以访问该端点;也可以设置为通配符(*)表示接受所有来源的请求。
#### 全局CORS配置
当需要更复杂的控制时,则应该考虑全局范围内的CORS策略定义。可以在应用启动类或任意@Configuration标记下的Java Config文件里实现WebMvcConfigurer接口并重写addCorsMappings方法:
```java
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("*") // 允许任何来源发起请求
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS"); // 支持的方法列表
}
}
```
上述例子设置了开放式的CORS规则给整个API服务[^2]。
#### 结合Spring Security使用
如果有集成Spring Security框架的情况,还需要特别注意开启CORS支持。可在Security配置中加入如下XML声明:
```xml
<http>
<!-- 默认采用Spring MVC内置的CORS机制 -->
<cors />
</http>
```
或者基于Java Config的形式完成相同功能:
```java
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final CorsConfigurationSource corsConfigurationSource;
@Bean
CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOriginPattern("*");
config.setMaxAge(3600L);
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return source;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().configurationSource(corsConfigurationSource).and()
...
}
}
```
这段代码实现了更加细粒度的安全性和灵活性管理的同时也确保了CORS的支持。
阅读全文
相关推荐


















