In this post under JJWT, I will explain how to create a simple unsecured JSON Web Token whose payload is a set of claims.
I will be using JJWT framework for this example and for all the upcoming examples under JJWT.
Below is the complete code for your reference
Main class
1 package defaultPackage;
2
3 import java.util.Date;
4
5 import io.jsonwebtoken.JwtBuilder;
6 import io.jsonwebtoken.Jwts;
7
8 public class Example1 {
9 public static void main(String[] args) {
10 JwtBuilder jwtBuilder = Jwts.builder();
11
12 jwtBuilder.header().add("alg", "none").add("typ", "JWT");
13
14 jwtBuilder.claims().subject("1234567890").issuedAt(new Date()).add("name", "Sumanth");
15
16 String jwt = jwtBuilder.compact();
17 System.out.println(jwt);
18 }
19 }
In the above code at line 10, I create an instance of “JwtBuilder” using static method “builder” of “Jwts” class.
At line 12, I configure the header information of the JWT. I set the “alg” to “none” since we are not signing it or encrypting it. I set the “type” to “JWT”.
At line 14, I configure the claims information of the JWT. It will be a map of key value pairs. As shown in the code, I entered subject, date the JWT was issued and name.
Here “subject” and “issuedAt” are predefined standard fields, whereas “name” is custom field added by us.
At line 16, I call “compact” method available on “JwtBuilder” instance. This will create a compact unsigned or unencrypted JWT.
In this way we can create a simple unprotected JWT containing claims.
Output
eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiIxMjM0NTY3ODkwIiwiaWF0IjoxNzA1NzM4Mzg5LCJuYW1lIjoiU3VtYW50aCJ9.