1

I would like to pass Role or Authorities in JWT for Redux, This due to have a better way to grant access according my desing (probably not the best), since I am middle level, I am getting confused in how to pass it while building jwt, this is the config (the way I learned);

public String generateToken(Authentication authentication){

    User user = (User) authentication.getPrincipal();
    Date now = new Date(System.currentTimeMillis());
    Date expiryDate = new Date(now.getTime()+ SecurityConstants.EXPIRATION_TIME); 
    String userId = Long.toString(user.getId());
   
    Map<String, Object> claims = new HashMap<>();
    claims.put("id", (Long.toString(user.getId())));
    claims.put("username", user.getUsername());


    return Jwts.builder() //WE create the token like this
            .setSubject(userId)
            .setClaims(claims)
            .setIssuedAt(now)
            .setExpiration(expiryDate)
            .signWith(SignatureAlgorithm.HS512, SecurityConstants.SECRET)
            .compact();
}

//Validate token in API
public boolean validateToken (String token){
    try{
        Jwts.parser().setSigningKey(SecurityConstants.SECRET).parseClaimsJws(token);
        return true;
    }catch (SignatureException ex){
        System.out.println("Invalid JWT signature");
    }catch (MalformedJwtException ex){
        System.out.println("Invalid JWT token");
    }catch (ExpiredJwtException ex){
        System.out.println("Expired JWT token");
    }catch (UnsupportedJwtException ex){
        System.out.println("Unsupported JWT token");
    }catch (IllegalArgumentException ex){
        System.out.println("JWT claims string is empty");
    } return false;
}

//GET userId from token
public Long getUserIdFromJWT(String token){
    Claims claims = Jwts.parser().setSigningKey(SecurityConstants.SECRET).parseClaimsJws(token).getBody();
    String id = (String)claims.get("id");

    return Long.parseLong(id);
}

I tried to add it in many ways in builder and generateToken either, but alwyas getting an error, I am expecting adding it in here;

jwt in Redux image

in user jwt i would like to pass role too. --->userRole: "ADMIN"<----

Any suggestion or support thank you in advance!

1 Answers1

0

You can use the Claims to set and get the user roles or just query the login / user Id into the database and check if it's authorized.

Is setting Roles in JWT a best practice?

Which in your example, you'll add this snippet right below the claim declaration

claims.put("role", user.getRole());