Creating and Parsing a secret key signed JWT containing claims

In this post under JWT, I will show with example how to create and parse a signed JWT containing claims.

As mentioned in previous posts we will use an instance of JwtBuilder to construct a JSON Web Token.

Below is the code snippet for your reference

Snippet 1


1    JwtBuilder jwtBuilder = Jwts.builder();
2        
3    Map<String, Object> headerMap = new HashMap<>();
4    headerMap.put("alg", "none");
5    headerMap.put("typ", Header.JWT_TYPE);
6        
7    jwtBuilder.setHeader(headerMap);
8        
9    Claims claims = Jwts.claims();
10    claims.setSubject("1234567890");
11    claims.setIssuedAt(new Date());
12    claims.put("name", "Sumanth");
13    jwtBuilder.setClaims(claims);
14        
15    String jwt = jwtBuilder.compact();

As you can see in the above code snippet, we create an instance of “JWTBuilder” named “jwtBuilder” at line 1.

From line 3 to 7, we create header information and assign it to “jwtBuilder”

From line 9 to 13, we create claims information and assign it to “jwtBuilder”

Finally at line 15, we generate the JWT by calling “compact” method on the instance “jwtBuilder”.

The JWT created following the above approach is an unsigned JWT.

To generate a signed JWT we have to configure the “jwtBuilder” to use a key, by taking help of “signWith” method. This method takes a key as an argument. After setting the key, any JWT generated by calling “compact” on the instance “jwtBuilder”, is a signed JWT.

Below is the code snippet that generates a signed JWT.

Snippet 2


1     JwtBuilder jwtBuilder = Jwts.builder();
2     jwtBuilder.signWith(secretKey);
3         
4     Map<String, Object> headerMap = new HashMap<>();
5     headerMap.put("alg", "HS512");
6     headerMap.put("typ", Header.JWT_TYPE);
7         
8     jwtBuilder.setHeader(headerMap);
9         
10    Claims claims = Jwts.claims();
11    claims.setSubject("1234567890");
12    claims.setIssuedAt(new Date());
13    claims.put("name", "Sumanth");
14    jwtBuilder.setClaims(claims);
15        
16    String jwtString = jwtBuilder.compact();

If we compare “Snippet 1” and “Snippet 2”, the only difference is the call to “signWith” to set the secret key. Refer to line 2 in “Snippet 2”.

Once the secretKey is set, the builder will use the secret key to generate a signed JWT.

Sometimes we don’t have to generate a signed JWT but instead we have to parse it.

From the previous post we can see that we use an instance of JwtParserBuilder to parse a unsigned JWT. Below is the code snippet for your reference

Snippet 3


1    JwtParserBuilder jwtParserBuilder = Jwts.parserBuilder();
2    JwtParser jwtParser = jwtParserBuilder.build();
3    Jwt<Header, Claims> jwt = jwtParser.parseClaimsJwt("eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJzdWIiOiIxMjM0NTY3ODkwIiwiaWF0IjoxNjYxNjU5OTU1LCJuYW1lIjoiU3VtYW50aCJ9.");

We use similar to code to parse a signed JWT.

All we have to do is configure JwtParserBuilder to use a secret key as shown below

Snippet 4


1    JwtParserBuilder jwtParserBuilder = Jwts.parserBuilder();
2    jwtParserBuilder.setSigningKey(secretKey);
3    JwtParser jwtParser = jwtParserBuilder.build();
4    Jws<Claims> jws = jwtParser.parseClaimsJws(data);

If we compare “Snippet 3” and “Snippet 4”, the only difference is the call to “setSigningKey” to set the secret key and the call to “parseClaimsJws” instead of “parseClaimsJwt”. Refer to line 2 in “Snippet 4”.

In the “Snippet 4”, the variable “data” is the string that contains the signed JWT.

Once the secret key is set to JwtParserBuilder, the builder will parse any signed JWT taking the help of the secret key.

The JJWT framework provides utility class named “io.jsonwebtoken.security.Keys” to generate secret key.

Below is the code snippet for generating secret key


SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS512);

In this way we can create and parse a secret key signed JWT containing claims.

Below is the complete code for your reference

Main Class


package defaultPackage;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.SecretKey;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Header;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.JwtParserBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

public class Example4 {
    public static void main(String[] args) throws Exception {
        Example4 example4 = new Example4();
        SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS512);
        String data = example4.toJWTString(secretKey);
        System.out.println(data);
        Jws<Claims> jws = example4.toJWS(secretKey, data);
        System.out.println(jws.getBody());
        System.out.println(jws.getSignature());
        System.out.println(jws.getHeader());
    }

    public String toJWTString(SecretKey secretKey) {
        JwtBuilder jwtBuilder = Jwts.builder();
        jwtBuilder.signWith(secretKey);

        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("alg", "HS512");
        headerMap.put("typ", Header.JWT_TYPE);

        jwtBuilder.setHeader(headerMap);

        Claims claims = Jwts.claims();
        claims.setSubject("1234567890");
        claims.setIssuedAt(new Date());
        claims.put("name", "Sumanth");
        jwtBuilder.setClaims(claims);

        String jwtString = jwtBuilder.compact();
        return jwtString;
    }

    public Jws<Claims> toJWS(SecretKey secretKey, String data) {
        JwtParserBuilder jwtParserBuilder = Jwts.parserBuilder();
        jwtParserBuilder.setSigningKey(secretKey);
        JwtParser jwtParser = jwtParserBuilder.build();
        Jws<Claims> jws = jwtParser.parseClaimsJws(data);
        return jws;
    }
}

Leave a Reply