In this post under JJWT, I will show with example how to parse a simple unsecured JSON Web Token containing claims as payload.
Below is the complete main code for your reference
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.parser();
12 jwtParserBuilder.unsecured();
13 JwtParser jwtParser = jwtParserBuilder.build();
14 Jwt<Header, Claims> jwt = jwtParser.parseUnsecuredClaims("eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJzdWIiOiIxMjM0NTY3ODkwIiwiaWF0IjoxNjYxNjU5OTU1LCJuYW1lIjoiU3VtYW50aCJ9.");
15 System.out.println(jwt.getHeader());
16 System.out.println(jwt.getPayload());
17 }
18 }
In the above code, at line 11, I create an instance of “JwtParserBuilder” class by name “jwtParserBuilder”
At line 12, I am telling the “jwtParserBuilder” instance that it has to parse unsecured JWT by calling “unsecured” method on the builder instance.
At line 13, I build the parser by calling “build” method on the builder instance.
At line 14, I parse the unsecured JWT by calling “parseUnsecuredClaims” method on the “JwtParser” instance.
At line 15, I print the header and at line 16 I print the payload.
In this way we can parse an unsecured JWT.
Output
{typ=JWT, alg=none}
{sub=1234567890, iat=1661659955, name=Sumanth}