springboot或security怎么在响应头中添加Access-Control-Allow-Origin字段
时间: 2024-11-12 11:15:51 浏览: 8
Spring Boot中的Spring Security可以轻松地处理跨域请求。为了在响应头中添加`Access-Control-Allow-Origin`字段,你需要在Spring Security的配置中设置CORS(Cross-Origin Resource Sharing)策略。以下是一个简单的例子:
首先,你需要添加Spring WebFlux和Spring Security CORS依赖:
```java
// pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-cors</artifactId>
</dependency>
```
然后在`application.properties`或`application.yml`文件中,启用CORS:
```properties
# application.properties
server.servlet.multipart.enabled=true
spring.mvc.cors.allowed-origin-patterns=*
spring.security.cors.enabled=true
spring.security.cors.add-origin-header=true
```
或者
```yaml
# application.yml
server:
servlet:
multipart:
enabled: true
security:
cors:
enabled: true
add-origin-header: true
allowed-origin-patters: "*"
```
在Controller层,如果你想要更精确地控制允许的origin,可以使用`@CrossOrigin`注解:
```java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@RestController
public class MyController {
@GetMapping("/api")
@CrossOrigin(allowedOrigins = "*", allowCredentials = "true", maxAge = 3600)
public Mono<String> getApi() {
// ... your logic here
return Mono.just("Hello from Spring Boot with CORS");
}
}
```
这将会允许所有来源(`"*"`),并允许带上凭证 (`allowCredentials="true"`),且预设了1小时的有效期 (`maxAge=3600`)。
阅读全文