skip to Main Content

So I am getting my JWT token with SecurityContext like so:

JwtAuthenticationToken authToken = (JWTAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();

if (authToken != null) {
    log.warn("Principal authorities:");
    authToken.getAuthorities().forEach(auth -> log.warn("authorities: [{}]", auth.getAuthority()));

Map<String, Object> attributes = Collections.emptyMap();
attributes = authToken.getTokenAttributes();

with my token looking something like:

{
  "exp": 1705347941,
  "iat": 1705347641,
  "jti": "011200ff-9c3d-44e4-8f49-be29fc0f7792",
  ...
  "user": [
    "backend",
    "backend-time"
  ],
  ...

How would grab all the values in user and assign them to a array of type String?

I am consoling my values like, but having trouble creating an string array with all user values.

attributes
    .entrySet()
    .forEach(attr -> log.warn("attributes: [{}:{}", attr.getKey(), attr.getValue()));

2

Answers


  1. You could do something like this:

    attributes = authToken.getTokenAttributes();
    List<String> userData = (List<String>) attributes.get("user");
    

    The .get() lets you get whatever data attributes contains. The code expects for that to be Object, therefore you have to add (List<String>) before getting the data, so the code knows that it is a list of string you will receive.

    Then all the strings within user is stored in said list. You could print the data any of these two ways:

    // To get first element
    log.warn(userData(0));
    
    // To get all elements
    for (int i = 0; i < userData.size(); i++) {
        log.warn(userData.get(i));
    }
    
    Login or Signup to reply.
  2. You can extract claims like below using the JWT token.

        private Claims extractAllClaims(String token) {
        return Jwts.parserBuilder().setSigningKey(getSigningKey()).build().parseClaimsJws(token)
                .getBody();
    }
    

    You will get a list like below.

    enter image description here

    You can use the below dependency.

        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-api</artifactId>
        </dependency>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search