简体   繁体   中英

Adding multiple claims In JWT token in Spring Boot microservice

I am trying to implement a JWT based token management in my microservice. I am using Spring Boot for developing service. Currently I created and send response to my front-end angular application with token. Here I only added claim and subject.

My code is like this:

public String generateUiaToken(String encodedSecret, Users uiaToken) {
    List<Integer> roleIdList = roleRepo.findRoleById((int) uiaToken.id);
    return Jwts.builder()
            .setId(UUID.randomUUID().toString())
            .setSubject(uiaToken.getUsername())
            .signWith(SignatureAlgorithm.HS512, encodedSecret)
            .claim("Role_List", roleIdList)
            .compact();
}

Here I added claim with a JSON role id list. How can I add more data about users with this structure or as claim?

THe purpose of JWT is to simply authenticate the user, we dont need to cram the JWT with data because if that is verified we can simply query whatever database we need with the username. I use passport in expressjs and I simply generate a JWT with my ID or username (both unique identifiers) and then push that in my Auth header on requests, my expressjs verifies the signature, and if so I can use that identifier (username or ID) with confidence the user themselves made this request, checking that users permissions, roles etc on the actual query instead of passing it in a JWT

You can add as much as claims as you want.You can do this by calling claims one more time.

Jwts.builder()
        .setId(UUID.randomUUID().toString())
        .setSubject(uiaToken.getUsername())
        .signWith(SignatureAlgorithm.HS512, encodedSecret)
        .claim("Role_List", roleIdList)
        .claim("abc", abcValue)
        .claim("asasas", asasas)
        .compact()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM