Creating a simple unsigned JSON Web Token containing claims

In this post under JJWT, I will explain how to create a simple unsigned JSON Web Token whose payload is a set of claims.

I will be using JJWT framework for this example and all the upcoming examples under JJWT.

Below is the complete code for your reference

Main Class

1  package defaultPackage;
3  import java.util.Date;
4  import java.util.HashMap;
5  import java.util.Map;
7  import io.jsonwebtoken.Claims;
8  import io.jsonwebtoken.Header;
9  import io.jsonwebtoken.JwtBuilder;
10 import io.jsonwebtoken.Jwts;
12 public class Example1 {
13     public static void main(String[] args) {
14         JwtBuilder jwtBuilder = Jwts.builder();
16         Map<String, Object> headerMap = new HashMap<>();
17         headerMap.put("alg", "none");
18         headerMap.put("typ", Header.JWT_TYPE);
20         jwtBuilder.setHeader(headerMap);
22         Claims claims =;
23         claims.setSubject("1234567890");
24         claims.setIssuedAt(new Date());
25         claims.put("name", "Sumanth");
26         jwtBuilder.setClaims(claims);
28         String jwt = jwtBuilder.compact();
29         System.out.println(jwt);
30     }
31 }

In the above code, at line 14, we create an instance of “JwtBuilder” class which will help us in creating Json Web Token. We will take the help of “Jwts” class static method “builder” to create the instance.

From line 16 to 18, we create a map and populate with JWT header information like algorithm and type.

At line 20, we call “setHeader” on jwtBuilder instance to set the newly created header map.

At line 22, we create an instance of “Claims” object. The class “Claims” represent the payload information in Json Web Token.

“Claims” class is nothing but a map, so in addition to providing predefined information like “Subject” (refer line 23) and “issued at” (refer line 24). We can provide more information
by calling the “put” method (refer to line 25).

At line 26, we call “setClaims” on jwtBuilder instance to set the newly created claims information.

Finally at line 28, we call the “compact” method on jwtBuilder instance to create the JWT. This method, will use all the information that we have provided like header and payload and create an unsigned JWT.

In this way we can create an unsigned JWT.



Leave a Reply