In this post under JJWT, I will show with example how to parse a simple unsigned JSON Web Token containing claims as payload.
Below is the complete main code.
Main class
1 package defaultPackage;
2 import io.jsonwebtoken.Claims;
3 import io.jsonwebtoken.Header;
4 import io.jsonwebtoken.Jwt;
5 import io.jsonwebtoken.JwtParser;
6 import io.jsonwebtoken.JwtParserBuilder;
7 import io.jsonwebtoken.Jwts;
8
9 public class Example2 {
10 public static void main(String[] args) {
11 JwtParserBuilder jwtParserBuilder = Jwts.parserBuilder();
12 JwtParser jwtParser = jwtParserBuilder.build();
13 Jwt<Header, Claims> jwt = jwtParser.parseClaimsJwt("eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJzdWIiOiIxMjM0NTY3ODkwIiwiaWF0IjoxNjYxNjU5OTU1LCJuYW1lIjoiU3VtYW50aCJ9.");
14 System.out.println(jwt.getHeader());
15 System.out.println(jwt.getBody());
16 }
17 }
In the above code, I create an instance of “JwtParserBuilder” using static method “parserBuilder” available on “Jwts” class. Refer to line 11.
At line 12, I create an instance of “JwtParser” with default configuration by calling “build” method on “jwtParserBuilder”.
Since our JWT payload will be a set of claims and it is unsigned, at line 13, we call “parseClaimsJwt” method on the instance of “jwtParser”.
The input to “parseClaimsJwt” is the unsigned JWT as shown at line 13.
The “parseClaimsJwt” parses the unsigned JWT and returns an instance of “Jwt” class which has “getHeader” and “getBody” method, through which we can get header and body details as shown in the below output. Refer to line 14 and 15.
Output
{typ=JWT, alg=none}
{sub=1234567890, iat=1661659955, name=Sumanth}
In this way, we can parse unsinged JWT containing claims.