Parse JWT token payload data to get certain value

2019-07-20 05:10发布

问题:

I just got introduced to the JWT and wanted to know how to parse the payload data to get a certain value from it using the key.

Example in the following JWT token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

The payload data contains the following object when decoded in jwt.io

{
    "sub" : "1234567890"
    "name" : "John Doe"
    "admin" : "true"
}  

I want to be able to parse this object to get the value of name which in this case is John Doe from the above JWT token.

I have already read this Android JWT parsing payload/claims when signed

But i wanted to know if there is efficient way to do this in android using some library. Any help would be appreciated.

回答1:

You can use Java JWT for that:

String name = Jwts.parser().setSigningKey(keyUsedWhenSigningJwt).parseClaimsJws("base64EncodedJwtHere").getBody().get("name", String.class);


回答2:

I solved it, by normally parsing the string and decoding it from base64 and then casting the string to JSONObject and parsing the JSONObject to get the required value.



标签: java android jwt