In this post under JJWT, I will show with example how to generate unsigned 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 unsigned JWT containing the payload.
Main Code
1 package defaultPackage;
2 import java.util.HashMap;
3 import java.util.Map;
4
5 import io.jsonwebtoken.Header;
6 import io.jsonwebtoken.JwtBuilder;
7 import io.jsonwebtoken.Jwts;
8
9 public class Example5 {
10 public static void main(String[] args) {
11 JwtBuilder jwtBuilder = Jwts.builder();
12
13 Map<String, Object> headerMap = new HashMap<>();
14 headerMap.put("alg", "none");
15 headerMap.put("typ", Header.JWT_TYPE);
16
17 jwtBuilder.setHeader(headerMap);
18
19 String payload = "Hi my name is Sumanth";
20 jwtBuilder.setPayload(payload);
21
22 String jwt = jwtBuilder.compact();
23 System.out.println(jwt);
24 }
25 }
In the above code, at line 11, we are creating an instance of “JwtBuilder” named “jwtBuilder”.
From line 13 to 17, we populate the header information and set it to “jwtBuilder” instance.
At line 20, we set the payload of the JWT by calling “setPayload” method on the “jwtBuilder” instance.
Then at line 22, 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.