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!
New contributor
daload is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.