feat: wire role-based authorities from JWT into Spring Security
- JwtAuthenticationFilter now extracts the "role" claim from the JWT
token and creates a SimpleGrantedAuthority("ROLE_" + role.toUpperCase())
on the authentication token. Previously the authorities list was
always empty (only userDetails.getAuthorities() which returned List.of())
- SecurityConfig adds .requestMatchers("/api/admin/**").hasRole("ADMIN")
so admin endpoints require the ROLE_ADMIN authority
- All existing endpoints remain authenticated() only — no existing user
flow is affected
- Public endpoints (auth, webhooks, vehicles) still permitAll()
This commit is contained in:
parent
fefdea089d
commit
8217b9c038
2 changed files with 10 additions and 1 deletions
|
|
@ -37,6 +37,7 @@ public class SecurityConfig {
|
||||||
.requestMatchers("/api/auth/register", "/api/auth/login").permitAll()
|
.requestMatchers("/api/auth/register", "/api/auth/login").permitAll()
|
||||||
.requestMatchers("/api/webhooks/**").permitAll()
|
.requestMatchers("/api/webhooks/**").permitAll()
|
||||||
.requestMatchers("/api/vehicles/**").permitAll()
|
.requestMatchers("/api/vehicles/**").permitAll()
|
||||||
|
.requestMatchers("/api/admin/**").hasRole("ADMIN")
|
||||||
.anyRequest().authenticated())
|
.anyRequest().authenticated())
|
||||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -45,8 +45,16 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||||
var userDetails = userDetailsService.loadUserByUsername(username);
|
var userDetails = userDetailsService.loadUserByUsername(username);
|
||||||
|
|
||||||
if (jwtService.isTokenValid(token)) {
|
if (jwtService.isTokenValid(token)) {
|
||||||
|
String role = jwtService.extractRole(token);
|
||||||
|
List<org.springframework.security.core.authority.SimpleGrantedAuthority> authorities =
|
||||||
|
new java.util.ArrayList<>();
|
||||||
|
if (role != null) {
|
||||||
|
authorities.add(new org.springframework.security.core.authority.SimpleGrantedAuthority(
|
||||||
|
"ROLE_" + role.toUpperCase()));
|
||||||
|
}
|
||||||
|
|
||||||
var authToken = new UsernamePasswordAuthenticationToken(
|
var authToken = new UsernamePasswordAuthenticationToken(
|
||||||
userDetails, null, userDetails.getAuthorities());
|
userDetails, null, authorities);
|
||||||
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
||||||
SecurityContextHolder.getContext().setAuthentication(authToken);
|
SecurityContextHolder.getContext().setAuthentication(authToken);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue