在Spring Security中配置跨域的步骤如下:
添加依赖:在pom.xml文件中添加对spring-boot-starter-web和spring-boot-starter-security的依赖。
创建一个配置类:创建一个名为WebSecurityConfig的配置类,并使用@EnableWebSecurity注解启用Web安全功能。
配置跨域:在WebSecurityConfig类中重写configure(HttpSecurity http)方法,并使用http.cors()方法配置跨域。
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors();
}
// 其他配置...
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
configuration.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type"));
configuration.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/**");
}
这些步骤完成后,Spring Security将会允许跨域请求。