Exceed maxRedirects error when making POST request with Spring Security Configuration

40 Views Asked by At

I'm encountering an error related to CORS and redifrection when attempting to make a POST request using Postman. The error message indicates, "Error: Exceeded maxRedirects. Probably stuck in a redirect loop http://localhost:8080/.

Here's a snipped of my security and controller in my application:


    @Configuration
    @EnableWebSecurity
    @RequiredArgsConstructor
    public class SecurityConfig{
    
    private final JwtAuthenticationFilter jwtAuthFilter;
    private final AuthenticationProvider authenticationProvider;
    
     @Bean
     public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
         String[] methods = {"GET", "POST"};
         List<String> allowedMethods = Arrays.asList(methods);
         
         http
             .cors( cors -> {
                 cors.configurationSource( request -> {
                     CorsConfiguration config = new CorsConfiguration();
                     config.setAllowedOrigins(Collections.singletonList("http://localhost:3000/"));
                     config.setAllowedMethods(allowedMethods);
                     return config;
                 });
             })
             .csrf( csrf -> csrf
                                .csrfTokenRepository(CookieCsrfTokenRepository
                                                        .withHttpOnlyFalse()))
             .authorizeHttpRequests(authorize -> authorize.requestMatchers("/api/v1/**").permitAll()
                     .anyRequest()
                     .authenticated()
             )
             .formLogin( form -> form
                                    .loginPage("/")
                                    .permitAll())
             .logout( logout -> logout
                                    .logoutUrl("/logOut")
             )
             .authenticationProvider(authenticationProvider)
             .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
             .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
             return http.build();
     }
}````

````Controller

    @RestController
    @RequiredArgsConstructor
    @CrossOrigin(origins = "https://localhost:3000", allowedHeaders ="*", methods = {RequestMethod.POST})
    @RequestMapping(path = "api/v1/authorize")
    public class AuthenticationController {

    private final AuthenticationService authenticationService;
    
    @PostMapping("/registration")
    public ResponseEntity<String> registration(
            @RequestBody RegisterRequest request
            ){
        try {
            authenticationService.register(request);
            return new ResponseEntity<>("User created successfully", HttpStatus.CREATED);
        } catch (DataAccessException ex) {
            ex.printStackTrace();
            return new ResponseEntity<>("We were unable to create the new user", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    @PostMapping("/authenticate")
    public ResponseEntity<AuthenticationResponse> authenticate(
            @RequestBody AuthenticationRequest request
            ){
        Status status = authenticationService.getStatusByEmail(request.getEmail());
        
        if(status.equals(Status.NEW)) {
            AuthenticationResponse authenticationResponse = new AuthenticationResponse(
                    "Unable to authenticate new user", null, null, null);
            return new ResponseEntity<>(authenticationResponse, HttpStatus.BAD_REQUEST);
        }else {
            Role role = authenticationService.getRoleByEmail(request.getEmail());
            String token =  authenticationService.authenticate(request);
            
            AuthenticationResponse authenticationResponse = AuthenticationResponse.builder()
                                                            .message("User Authenticated Successfully")
                                                            .token(token)
                                                            .email(request.getEmail())
                                                            .role(role )
                                                            .build();
            
            return ResponseEntity.ok(authenticationResponse);
        }
        
    }
}

I was expecting to receive an Authentication Response in json format.

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public class AuthenticationResponse {

    private String message;
    private String token;
    private String email;
    private Role role; 
    
    }
0

There are 0 best solutions below