Home > other >  Extracting values from jwt token
Extracting values from jwt token

Time:09-23

I am trying to create a new user and authenticate the user using JWT token. The token is getting created but when I try to extract values from the token, all the values are being returned as null. jwtUtil.extractClaims() is supposed to extract the values from the token but all values are null.

@GetMapping("/register/code/{token}")
public HashMap<String, Object> register(@PathVariable("token") String token, HttpServletResponse httpServletResponse) {
   HashMap<String, Object> response = new HashMap<>();
   System.out.println(token);
    if (!jwtUtil.isTokenExpired(token)){
        System.out.println("User");
        User user = new User(
                (String) jwtUtil.extractAllClaims(token).get("email"),
                (String) jwtUtil.extractAllClaims(token).get("phoneNumber"),
                (String) jwtUtil.extractAllClaims(token).get("ppUrl"),
                (String) jwtUtil.extractAllClaims(token).get("password")
        );
        System.out.println("User email " jwtUtil.extractAllClaims(token).get("email"));
        String encodedPassword = passwordEncoder.encode(user.getPassword());
        // System.out.println(encodedPassword   " THIS IS THE ENCODED PASSWORD"  
        // authenticationRequest.getPassword());
        user.setPassword(encodedPassword);
        if (user.getProfilePicture() == null) {
            user.setProfilePicture("default.png");
        }
        User savedUser = userRepository.save(user);
        response.put("success", true);
        response.put("message", "User Registered is Succesfull");
        System.out.println("mail verified");
        try {
            httpServletResponse.sendRedirect("/app");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    } else {
        response.put("success", false);
        response.put("message", "User Registered is not Succesfull!");
        return response;
    }
}

The extractClaims() is as follows:

public Claims extractAllClaims(String token) {
    System.out.println(Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody());
    return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
}

How else can I extract the values from the token.

Edited to add the token generation code:

public String generateToken(User user) {
    Map<String, Object> claims = new HashMap<>();
    claims.put("user", user);
    return createToken(claims);
}

private String createToken(Map<String, Object> claims) {
    System.out.println("Claims inside createToken " claims);
    return Jwts.builder().setClaims(claims).setIssuedAt(new Date(System.currentTimeMillis()))
           .setExpiration(new Date(System.currentTimeMillis()   1000 * 60 * 60 * 10))
          .signWith(SignatureAlgorithm.HS256, secret).compact();
}

CodePudding user response:

Try with extractClaim and not extractAllClaims. So like this:

public String extractUsername(String token) {
    return extractClaim(token, Claims::getSubject);
}

And create the method extractClaim:

public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
    final Claims claims = extractAllClaims(token);
    return claimsResolver.apply(claims);
}

Edit: You should add the user while doing the Jwts builder with setSubject:

return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
       .setExpiration(new Date(System.currentTimeMillis()   1000 * 60 * 60 * 10))
      .signWith(SignatureAlgorithm.HS256, secret).compact();

CodePudding user response:

The only problem with your code is that you add an object (user) to Claims and call the value of the object in Claims without calling the object (user).

First you need to take the object in your hand and get the information from it.

Try creating a user like this:

System.out.println("User");
LinkedHashMap userVariables = jwtUtil.extractAllClaims(token)
                .get("user", LinkedHashMap.class);
User user = new User(
        (String) userVariables.get("email"),
        (String) userVariables.get("phoneNumber"),
        (String) userVariables.get("ppUrl"),
        (String) userVariables.get("password")
);
  • Related