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

How to Integrate Spring Security CORS Filter?

Mary-Kate Olsen
Release: 2024-11-01 12:52:22
Original
263 people have browsed it

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>
    Copy after login
  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>
    Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template