javaspringspring-boot

Spring Boot Security always returns 403 on all errors except success


I'm learning about Spring Boot and trying to configure the Security Filter Chain with JWT.
I'm facing a problem where it always returns 403 errors. For example, when I access a non-existent URL, it throws a 403 error, and in the case of an invalid request body, it throws a 403 error again. Other errors also occur. However, in the case of success, it works correctly.
Can anyone tell me what my fault is? Thanks a lot.

My SecurityFilterChain:

@Configuration
@EnableWebSecurity
public class SecurityConfig {
 private final JwtRequestFilter jwtRequestFilter;
 @Autowired
 public SecurityConfig(JwtRequestFilter jwtRequestFilter) {
    this.jwtRequestFilter = jwtRequestFilter;
 }
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) {
    try {
        httpSecurity
                .csrf(csrf -> csrf.csrfTokenRepository(cookieCsrfTokenRepository()).disable())
                .authorizeHttpRequests(authorize -> authorize.requestMatchers("/api/v1/*/public/**", "/api/v1/auth/login")
                        .permitAll().anyRequest().authenticated())
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
        return httpSecurity.build();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
@Bean
public CsrfTokenRepository cookieCsrfTokenRepository() {
    return CookieCsrfTokenRepository.withHttpOnlyFalse();
  }
}

JwtRequestFilter :

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {
        chain.doFilter(request, response);
}

My Dependencies:

implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'io.jsonwebtoken:jjwt-api:0.11.2'

Solution

  • Thanks to M.Deinum, I learned that: In case of an error, it redirects to /error. I made a few modifications and it worked.