skip to Main Content

I created a very simple SpringBoot app (pretty much a CRUD) and added JWT auth for users. The requests are all tested with postman and are working fine and interacting with the db without in cloud without any issues. My configuration class looks like this:

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class WebSecurityConfig {

private final JwtAuthenticationFilter jwtAuthFilter;
private final AuthenticationProvider authenticationProvider;

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http, JwtAuthenticationFilter jwtAuthenticationFilter) throws Exception {
    http
            .csrf(AbstractHttpConfigurer::disable)
            .cors(Customizer.withDefaults())
            .authorizeHttpRequests((authorizeHttpRequests) ->
                    authorizeHttpRequests
                            .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                            .requestMatchers("/auth/**").permitAll()
                            .anyRequest().authenticated()
            )
            .sessionManagement((sessionManagement) ->
            sessionManagement
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    )
            .authenticationProvider(authenticationProvider)
            .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);

    return http.build();
}}

The issue I get is that even though with this configuration the requests are working fine with postman, when I make the same request from a React App I’m getting the errors:
enter image description here
I’m not sure what configuration could be missing. In console I get:
enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    The issue was the order in the config class, after changing:

    .csrf(AbstractHttpConfigurer::disable)
    .cors(Customizer.withDefaults())
    

    to:

    .cors(Customizer.withDefaults())
    .csrf(AbstractHttpConfigurer::disable)
    

    it worked just fine


  2. You need to allow the host of the client:

      ...
      .cors().configurationSource(corsConfigurationSource())
      ...
    
      @Bean
      public CorsConfigurationSource corsConfigurationSource() {
            CorsConfiguration configuration = new CorsConfiguration();
            configuration.addAllowedOrigin("http://localhost:5174");
            configuration.addAllowedMethod("*");
            configuration.addAllowedHeader("*");
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", configuration);
            return source;
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search