在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將會允許跨域請求。