Home >Java >javaTutorial >How to Integrate Spring Security CORS Filter?
Spring Security CORS Filter Integration
Spring Security requires CORS configuration to handle cross-origin requests. To address this issue specifically, follow these steps:
Implement a WebMvcConfigurerAdapter:
<code class="java">@Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH"); } }</code>
Configure CORS in HttpSecurity:
<code class="java">@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().configurationSource(corsConfigurationSource()); } @Bean public CorsConfigurationSource corsConfigurationSource() { final CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(ImmutableList.of("*")); configuration.setAllowedMethods(ImmutableList.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH")); configuration.setAllowCredentials(true); configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type")); final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } }</code>
Important Notes:
The above is the detailed content of How to Integrate Spring Security CORS Filter?. For more information, please follow other related articles on the PHP Chinese website!