I have created an authentication system in Springboot, which checks the user, if it exists, I create a jwt token that is sent to the front and the front returns it to make requests, this token has the role incorporated.
private static final String AUTHORITIES_KEY = "auth";
static void addAuthentication(HttpServletResponse res, Authentication authentication) {
String token = Jwts.builder()
.setSubject(authentication.getName())
.setExpiration(new Date(System.currentTimeMillis() + timeout))
.signWith(SignatureAlgorithm.HS512, key)
.claim(AUTHORITIES_KEY, authentication.getAuthorities()) // El rol es "ROLE_Consulta"
.compact();
res.addHeader("Authorization", "Bearer " + token);
}
For the user I'm using, his role is query, so I add in the controller:
@Secured("ROLE_Consulta")
So when I send the token from the front, I try to decompose it to create the user to access the system:
**EDITO:**
static Authentication getAuthentication(HttpServletRequest request) {
// Obtenemos el token que viene en el encabezado de la peticion
String token = request.getHeader("Authorization");
// si hay un token presente, entonces lo validamos
if (token != null) {
String user = Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(token.replace("Bearer", "")) // este metodo es el que valida
.getBody().getSubject();
Claims claims = Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(token.replace("Bearer", ""))
.getBody();
Collection authorities = Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(","))
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
return user != null ? new UsernamePasswordAuthenticationToken(user, null, authorities) : null;
}
return null;
}
}
As you can see in the image, I have the ROLE_Query role, but I get the AccessDeniedException error.
"status": 403,
"error": "Forbidden",
"exception": "org.springframework.security.access.AccessDeniedException",
"message": "Acceso denegado",
I've solved it by decomposing the authorities and getting the role and then inserting a different class than the UsernamePasswordAuthenticationToken, It's not very elegant, but it works.