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 recap

Snippet 1

1 JwtBuilder jwtBuilder = Jwts.builder();
2
3 jwtBuilder.header().add("alg", "none").add("typ", "JWT");
4
5 jwtBuilder.claims().subject("1234567890").issuedAt(new Date()).add("name", "Sumanth");
6
7 String jwt = jwtBuilder.compact();

In the above code snippet, at line 1 I created an instance of “JwtBuilder” class named “jwtBuilder”.

At line 3, I configure the header information

At line 5, I configure the claims information

At line 7, I generate the token by calling “compact” method on “jwtBuilder” instance.

The JWT created following the above approach is an unsecured 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 secret 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 1

1 JwtBuilder jwtBuilder = Jwts.builder();
2 jwtBuilder.signWith(secretKey);
3
4 jwtBuilder.header().add("alg", "HS512").add("typ", "JWT");
5
6 jwtBuilder.claims().subject("1234567890").issuedAt(new Date()).add("name", "Sumanth");
7
8 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 recap

Snippet 3

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

We use similar code to parse signed JWT as shown in the below snippet

Snippet 4

1 JwtParserBuilder jwtParserBuilder = Jwts.parser();
2 jwtParserBuilder.verifyWith(secretKey);
3 JwtParser jwtParser = jwtParserBuilder.build();
4 Jws<Claims> jws = jwtParser.parseSignedClaims(data);

If we compared “snippet 3” and “snippet 4”, they are two differences (line 2 and line 4).

In line 2 of snippet 4, we have to call “verifyWith” method on “jwtParserBuilder” instance and pass the secret key as an argument. We no longer need to call “unsecured” method as done in “snippet 3”.

Remember we need to use same secret key that is used to generate the signed JWT.

In line 4 of snippet 4, we have to call “parseSignedClaims” method on “jwtParser” instance to parse the signed JWT. We no longer need to call “parseUnsecuredClaims” method as done in “snippet 3”.

In this way we can generate and parse a signed JWT.

Below is the complete main code for your reference.

Main class


package defaultPackage;
import java.util.Date;

import javax.crypto.SecretKey;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.JwtParserBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.MacAlgorithm;

public class Example4 {
    public static void main(String[] args) throws Exception {
        Example4 example4 = new Example4();
        MacAlgorithm macAlgorithm = Jwts.SIG.HS512;
        SecretKey secretKey = macAlgorithm.key().build();
        String data = example4.toJWTString(secretKey);
        System.out.println(data);
        Jws<Claims> jws = example4.toJWS(secretKey, data);
        System.out.println(jws.getHeader());
        System.out.println(jws.getPayload());
    }

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

        jwtBuilder.header().add("alg", "HS512").add("typ", "JWT");

        jwtBuilder.claims().subject("1234567890").issuedAt(new Date()).add("name", "Sumanth");

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

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


Leave a Reply