springboot security 如何设置Access-Control-Allow-Origin
时间: 2023-06-28 14:13:08 浏览: 74
在Spring Boot中,可以通过配置WebSecurityConfigurerAdapter来设置Access-Control-Allow-Origin。以下是一个示例:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.cors()
.and()
.authorizeRequests()
.antMatchers("/api/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("Content-Type", "Authorization"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
```
上述代码中,我们首先禁用了Spring Security的CSRF保护,然后启用了Cors配置。在corsConfigurationSource()方法中,我们设置允许所有来源(allowedOrigins)的请求,允许的HTTP方法(allowedMethods)为GET、POST、PUT、DELETE和OPTIONS,允许的请求头(allowedHeaders)为Content-Type和Authorization。最后,我们将Cors配置注册到所有URL上。
这样就可以在Spring Boot中设置Access-Control-Allow-Origin了。