I have a jwt token like this
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
How can I decode this so that I can get the payload like this
{ "sub": "1234567890", "name": "John Doe", "admin": true }
I have used this library , but can't find a way to do what I want
By design, anyone can decode a JWT and read the contents of the header and payload sections. But we need access to the secret key used to create the signature to verify a token's integrity.
There are two ways in which a public/private keys can be used by a JWT: signing and encryption. If you use a private key for signing, it allows for the recipient to identify the sender of the JWT and the integrity of the message but not to hide its contents from others (confidentiality).
you should split string: If you pass the first two sections through a base 64 decoder, you'll get the following (formatting added for clarity):
header
{ "alg": "HS256", "typ": "JWT" }
body
{ "sub": "1234567890", "name": "John Doe", "admin": true }
Code example:
public class JWTUtils { public static void decoded(String JWTEncoded) throws Exception { try { String[] split = JWTEncoded.split("\\."); Log.d("JWT_DECODED", "Header: " + getJson(split[0])); Log.d("JWT_DECODED", "Body: " + getJson(split[1])); } catch (UnsupportedEncodingException e) { //Error } } private static String getJson(String strEncoded) throws UnsupportedEncodingException{ byte[] decodedBytes = Base64.decode(strEncoded, Base64.URL_SAFE); return new String(decodedBytes, "UTF-8"); } }
Call method for example
JWTUtils.decoded("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ");
library reference: https://github.com/jwtk/jjwt
jwt test: https://jwt.io/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With