29 March 2016

Introduction to Json Web Token




JSON web tokens are specifically for pass data between two parties securly.It is a industry standard protocol format.[https://tools.ietf.org/html/rfc7519]. In this tutorial i am mainly going to talk about how JWT is useful for client to server communication.Let’s assume you have http client and you need to communicate to rest server.So basically there are different ways to secure your connection.


  1. HTTPS
  2. User name password based authentication
  3. Pass custom secure   element using http header.

We all know that HTTPS is the secure way to communicate via HTTP protocol. But it is costly.So token based authentication gives the best security for your API design.


Usage Of JWT


JWT use for token based authentication.Token based authentication helps to authenticate server and client stateless. So No need to store client data in server side(Like sessions).

So Let’s see how JWT work in API.First when client login using username and password Then server validate the credentials and generate sign token and sent to client.Then client store token and every request send token with header.Then server verify the token and validate request.

Structure of JWT


Jason web token is this type.
aaaaa.bbbbbb.cccc So It have three parts.

Header
Payload
Signature

Header contains algorithm and type of token.

Payload is simply data you want to exchange two parties. These data type called as clams. There are two type of clams (Public and Private).
Ex:-
iss (issuer)
exp (expiration time)
sub (subject)
aud (audience)

Signature is the most advance part in web token. signature made using using this structure. Algorithem(base64urlencode(header) +"."base64urlencode(payload)+ secret)

Implementation Of JWT

There are lot of libraries available for creating and validate JSON web tokens.In this tutorial I have used this library.


1
2
3
4
5
<dependency>
    <groupid>org.bitbucket.b_c</groupid>
    <artifactid>jose4j</artifactid>
    <version>0.4.4</version>
</dependency>

Create JASON web token.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public String generateToken(String userName) {
        String jwt = null;
        try {
            JwtClaims claims = new JwtClaims();
            claims.setIssuer(userName);
            claims.setExpirationTimeMinutesInTheFuture(expiryTimeInMinutes);
            claims.setGeneratedJwtId();
            claims.setIssuedAtToNow();
            claims.setNotBeforeMinutesInThePast(beforeTimeTest);
            claims.setSubject(subject);


            JsonWebSignature jws = new JsonWebSignature();
            jws.setPayload(claims.toJson());
            jws.setKey(rsaJsonWebKey.getPrivateKey());
            jws.setKeyIdHeaderValue(rsaJsonWebKey.getKeyId());
            jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

            jwt = jws.getCompactSerialization();
            logger.info("Token Created {}", jwt);

        } catch (JoseException e) {
            logger.error("Creating Token Failed {}", e);
        } catch (Exception ex) {
            logger.error("Error occurred while Creating Token {}", ex);
        }
        return jwt;
    }
Most important thing is creating token we can set expiration time so when authentication token from server side if token is expired then it helps to easily authenticate token.As example when user first login to system we create token send and then sequentially request by request client append that token to header and send to server.

Validating Web Token


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public boolean validateToken(String token) {
        boolean state;
        JwtConsumer jwtConsumer = new JwtConsumerBuilder()
                .setRequireExpirationTime()
                .setAllowedClockSkewInSeconds(30)
                .setRequireSubject()
                .setRequireExpirationTime()
                .setVerificationKey(rsaJsonWebKey.getKey())
                .build();

        try {
            JwtClaims jwtClaims = jwtConsumer.processToClaims(token);
            long expiredDateTime = jwtClaims.getExpirationTime().getValueInMillis();
            Date date = new Date(expiredDateTime);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            logger.info("Token Expired Date : " + simpleDateFormat.format(date));
            state = true;
        } catch (InvalidJwtException e) {
            state = false;
            logger.debug("Error Occurred while validating JWT {}", e);
        } catch (MalformedClaimException e) {
            state = false;
        }
        return state;
    }

Above method validate Web Token if token expired it will throw exception. Hope you got some understand what is JSON web token and usage of web tokens.If you have any question feel free to comment in here.Thanks.