springspring-bootspring-securityjwt

API can't access to private endpoints (403 Forbidden) even though user is authenticated


I think what is wrong is my authenticationFilter.

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    final String token = getTokenFromRequest(request);
    final String username;
    if (token == null) {
        filterChain.doFilter(request, response);
        return;
    }
    username = jwtService.getUsernameFromToken(token);
    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (jwtService.isTokenValid(token, userDetails)) {
            UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                    userDetails,
                    null,
                    userDetails.getAuthorities());
            authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authToken);
        }
    }
    filterChain.doFilter(request, response);
}

The userdetails get added to the security context as expected but then the doFilter messes it up. What I might be doing wrong? This is the SecurityConfig:

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final JwtAuthenticationFilter jwtAuthenticationFilter;
    private final AuthenticationProvider authProvider;
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
            .csrf(csrf->
                csrf.disable())
            .authorizeHttpRequests(authRequest ->
                authRequest
                    .requestMatchers("/auth/**").permitAll()
                    .anyRequest().authenticated()
            )
            .sessionManagement(sessionManager ->
                sessionManager.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authenticationProvider(authProvider)
            .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
            .build();
    }
}

I'm always getting a 403 Forbidden response in Postman.

Any ideas what might be wrong? Debugged but I cannot find the issue. I'm missing something (probably stupid) but cannot find it.
Thanks in advance!

EDIT: Those are the logs with LogLevel DEBUG:

2024-07-01T11:50:08.830-07:00 DEBUG 15809 --- [WorkLogAPI] [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : Securing POST /api/v1/demo/
Hibernate: select u1_0.id,u1_0.password,u1_0.role,u1_0.username from wluser u1_0 where u1_0.username=?
2024-07-01T11:50:33.405-07:00 DEBUG 15809 --- [WorkLogAPI] [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : Secured POST /api/v1/demo/
2024-07-01T11:50:33.442-07:00 DEBUG 15809 --- [WorkLogAPI] [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : Securing POST /error
2024-07-01T11:50:33.443-07:00 DEBUG 15809 --- [WorkLogAPI] [nio-8080-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-07-01T11:50:33.444-07:00 DEBUG 15809 --- [WorkLogAPI] [nio-8080-exec-3] o.s.s.w.a.Http403ForbiddenEntryPoint     : Pre-authenticated entry point called. Rejecting access

Solution

  • Thanks to @dur I got this solved!

    I had my /error endpoint secured so 403 was being responded. Adding .requestMatchers("/error").permitAll() to my securityFilterChain solved the issue.

    Sorry for all of you that saw a similar question to Spring Boot 3 with Spring Security Intercepts exceptions I don't want it to Honestly I didn't know this was the issue so I did not do any research in that direction. Thanks to all of those that invested time in helping!!

    Now I'm curious as why this happens. Guess I'll do some research about this now.