-1

I'm using a SecurityFilterChain to manage my Security:

First, added .cors().and() filter to my SecurityChain

    JWTAuthenticationFilter jwtAuthenticationFilter = new JWTAuthenticationFilter();
    jwtAuthenticationFilter.setAuthenticationManager(authManager);
    jwtAuthenticationFilter.setFilterProcessesUrl("/login");

    return http
            .cors().and()
            .csrf().disable()
            .authorizeHttpRequests()
            .anyRequest().authenticated()
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .addFilter(jwtAuthenticationFilter)
            .addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class)
            .build();

Then, created a corsConfiguration bean but still doesn't work as expected

    @Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("http://localhost:3000/")
                    .allowedMethods("GET", "OPTIONS", "POST")
                    .allowedHeaders("Authorization")
                    .allowCredentials(true);;
        }
    };
}
  • CORS is the MOST asked question when it comes to the spring security tag, it gets asked 5 times a week. there are 100s of questions that handles this also there is an entire chapter in the spring security documentation about CORS https://docs.spring.io/spring-security/reference/reactive/integrations/cors.html#page-title https://stackoverflow.com/questions/36968963/how-to-configure-cors-in-a-spring-boot-spring-security-application downvoted becuase bad research you have posted no debug logs, have you verified that your bean is loaded, and have you debugged your application? – Toerktumlare Feb 06 '23 at 00:33
  • @Toerktumlare Although everything you've written is true, users facing a CORS issue often don't know where to begin and are let down by sub-par tools (exhibit A: why doesn't Spring validate user-specified origins?). Better nudge them in the right direction than admonish them. – jub0bs Feb 06 '23 at 08:25

1 Answers1

0

I solved it by separating my @Bean into another class like this:

//remember to add ".cors().and()" to you SecurityFilterChain

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:3000/")
                .allowedHeaders("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE");
    }
    
}

Also had to add this line to be able to manipulate my Authorization token

   .exposedHeaders("Authorization");