Parsing simple unsigned JWT containing plaintext as payload

In this post under JJWT, I will show with example how to parse unsigned JWT containing plaintext as payload instead of serialized Claims object.

As shown in previous post under JJWT, whenever we need to parse a JWT string. We need to create an instance of “JwtParser” as shown below

    JwtParserBuilder jwtParserBuilder = Jwts.parser();
jwtParserBuilder.unsecured();
JwtParser jwtParser = jwtParserBuilder.build();

As shown in the above code, first we create an instance of “JwtParserBuilder” from “Jwts” class by calling its static method “parser”.

Next we configure JwtParserBuilder instance to parse unsecured JWT by calling “unsecured” method on builder instance.

Next we create an instance of “JwtParser” by calling “build” method on “jwtParserBuilder” instance.

In my previous posts I showed how to parse a unsigned JWT containing claims data by calling “parseUnsecuredClaims” method on “JwtParser” instance.

Similar to “parseUnsecuredClaims” there is a corresponding instance method by name “parseUnsecuredContent” in “JwtParser” instance.

We use this method to parse unsecured JWT containing plaintext.

Below is the complete code for your reference

Main class

package defaultPackage;
import io.jsonwebtoken.Header;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.JwtParserBuilder;
import io.jsonwebtoken.Jwts;

public class Example6 {
public static void main(String[] args) {
JwtParserBuilder jwtParserBuilder = Jwts.parser();
jwtParserBuilder.unsecured();
JwtParser jwtParser = jwtParserBuilder.build();
Jwt<Header, byte[]> jwt = jwtParser.parseUnsecuredContent("eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.SGkgbXkgbmFtZSBpcyBTdW1hbnRo.");
System.out.println(jwt.getHeader());
System.out.println(new String(jwt.getPayload()));
}
}

In this way we can parse an unsecured JWT containing payload.

Output

{typ=JWT, alg=none}
Hi my name is Sumanth

Leave a comment