javaspringhttp-status-code-403

Always getting 403 Forbidden error even thought it should return 404 Not Exists (Java Spring application problem)


I am having the problem with Java 17 Spring Maven application because it always returns to me 403 Forbidden status in Postman when I test my code. I locate the problem within securityFilterChain() method but I am not sure how could I fix this.

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfiguration {

    private final JwtAuthenticationFilter jwtAuthFilter;

    private final AuthenticationProvider authenticationProvider;
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/api/v1/city/**").permitAll()
                        .requestMatchers("/api/v1/auth/**").permitAll()
                        .anyRequest().authenticated()
                )
                .csrf(AbstractHttpConfigurer::disable)
                .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authenticationProvider(authenticationProvider)
                .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}

Has anyone experienced similar problem.

Thanks in advance!

When I disabled:

.authenticationProvider(authenticationProvider)
      .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);

and

.requestMatchers("/api/v1/city/**").permitAll()
.requestMatchers("/api/v1/auth/**").permitAll()

Then it gives right response but then I disable JWT Authentication

Example of problem

Example of problem


Solution

  • You are being redirected to /error page which is secured by spring-security. so you should permit it

    add

    .requestMatchers("/error").permitAll()