Creating a simple unsecured JSON Web Token containing payload

In this post under JJWT, I will show with example how to generate unsecured JWT containing payload.

In previous post under JJWT, I talked about JWT containing claims.

So what is the difference between claims and payload. Its simple, payload is noting but any String data, whereas claims is a map.

Now with the difference between claims and payload is clear, lets see the code that will generate unsecured JWT containing the payload.

Below is the main code for your reference

Main class

1  package defaultPackage;
2 import io.jsonwebtoken.JwtBuilder;
3 import io.jsonwebtoken.Jwts;
4
5 public class Example5 {
6 public static void main(String[] args) {
7 JwtBuilder jwtBuilder = Jwts.builder();
8
9 jwtBuilder.header().add("alg", "none").add("typ", "JWT");
10
11 String payload = "Hi my name is Sumanth";
12 jwtBuilder.content(payload);
13
14 String jwt = jwtBuilder.compact();
15 System.out.println(jwt);
16 }
17 }

In the above code, at line 17, we are creating an instance of “JwtBuilder” named “jwtBuilder”.

At line 9, we populate the header information.

At line 12, we populate the payload by calling the “content” method on “jwtBuilder” instance.

Then at line 14, we call “compact” method on “jwtBuilder” instance to generate the JWT token using the header and payload information provided previously.

In this way, we can generate JWT token containing a payload.

Leave a comment