Home  >  Article  >  Java  >  How to Integrate Spring Security CORS Filter?

How to Integrate Spring Security CORS Filter?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 12:52:22190browse

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:

  1. 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>
  2. 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:

  • Avoid using http.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll(); or web.ignoring().antMatchers(HttpMethod.OPTIONS);, as they are incorrect solutions.
  • Refer to the official Spring Security documentation for more details: http://docs.spring.io/spring-security/site/docs/4.2.x/reference/html/cors.html

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn