I am working with Spring Security and a custom JWT authentication filter, but I am facing an issue where I’m getting a 403 Forbidden error when trying to access endpoints that require specific roles. The permitAll() configuration works fine, but using hasRole() or hasAnyAuthority() doesn’t seem to work.
Here’s my Spring Security configuration:
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth ->
auth.requestMatchers("/v1/api/public/**").permitAll()
.requestMatchers("/v1/api/authorized/**").hasRole("USER")
.anyRequest().authenticated())
.sessionManagement(sessionManagement ->
sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); // Add custom filter
return http.build();
}
Here’s my custom JWT filter:
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtService jwtService;
private final UserService userService;
public JwtAuthenticationFilter(JwtService jwtService, UserService userService) {
this.jwtService = jwtService;
this.userService = userService;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
final String header = request.getHeader("Authorization");
if (header != null && header.startsWith("Bearer ")) {
final String jwt = header.substring(7);
String username = jwtService.extractUsername(jwt);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
User user = userService.getUserByUsername(username);
if (jwtService.validateToken(jwt, user)) {
CustomUserDetails userDetails = new CustomUserDetails(user);
// Create an authentication token
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
// Set the authentication token in the SecurityContext
SecurityContextHolder.getContext().setAuthentication(authToken);
}
}
}
// Continue the filter chain
filterChain.doFilter(request, response);
}
}
And my CustomUserDetails class:
public class CustomUserDetails implements UserDetails {
private final User user;
public CustomUserDetails(User user) {
this.user = user;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return List.of(new SimpleGrantedAuthority("ROLE_USER"), new SimpleGrantedAuthority("ROLE_ADMIN"));
}
@Override
public String getPassword() {
return user.getPassword();
}
@Override
public String getUsername() {
return user.getEmail();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
public User getUser() {
return user;
}
}
Problem:
When I try to access an endpoint that requires a role (@PreAuthorize(“hasRole(‘USER’)”) or hasRole(“USER”)), I am still getting a 403 Forbidden error.
However, permitAll() works fine, meaning the filter is properly executed and the JWT is being validated.
What I’ve Tried:
I’ve tried using both hasRole(“USER”) and hasAnyAuthority(“ROLE_USER”, “ROLE_ADMIN”) but neither works.
I checked the GrantedAuthority and the roles in SecurityContextHolder, and they are being set correctly as ROLE_USER and ROLE_ADMIN.
I am using the @PreAuthorize annotation on controller methods as well.
Expected Behavior:
I expect the user with the ROLE_USER or ROLE_ADMIN to be granted access to the /v1/api/authorized/** endpoints without receiving a 403 error.
Any help would be greatly appreciated!
Make sure that the role column in your database or any datasource also has the prefix “ROLE_”(make sure they are stored with the prefix also)
1
The issue is that method-level security annotations like @PreAuthorize require explicit enabling. Add @EnableMethodSecurity to your security configuration class:
@Configuration
@EnableMethodSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth ->
auth.requestMatchers("/v1/api/public/**").permitAll()
.requestMatchers("/v1/api/authorized/**").hasRole("USER")
.anyRequest().authenticated())
.sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}
This enables method-level security, allowing @PreAuthorize to work correctly. For more details, refer to the Spring Security Documentation.
1