Build Secure Application Using JSON Web Tokens (JWT)

JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.

Below picture will give more better explanation

The claims in a JWT are encoded as a JSON object that is base64url encoded and consists of zero or more name/value pairs (or members), where the names are strings and the values are arbitrary JSON values. Each member is a claim represented by the JWT.

What JWT contains – JWT consists of three main components: a header object, payload object, and a signature. These three properties are encoded using base64, then concatenated with periods as separators.

for example

xxxxxxxxxxxxxxxxxx.yyyy.zzzzzzzzzzzzzzzzzzzzzzzzz

xxxxxxxxxxxxxxxxxxxxx – header
yyyy – – claims/payload
zzzzzzzzzzzzzzzzzzzz – signature

Header: The header contains the metadata for the token and at a minimal contains the type of the signature and/or encryption algorithm
Claims: The claims contains any information that you want signed
JSON Web Signature (JWS): The headers and claims digitally signed using the algorithm in the specified in the headerStructure of a JWT

JSON Web Token example:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0b3B0YWwuY29tI iwiZXhwIjoxNDI2NDIwODAwLCJodHRwOi8vdG9wdGFsLmNvbS9qd3RfY2xhaW1zL2lzX2FkbWluI jp0cnVlLCJjb21wYW55IjoiVG9wdGFsIiwiYXdlc29tZSI6dHJ1ZX0.yRQYnWzskCZUxPwaQupWk iUzKELZ49eM7oWxAQK_ZXw

Since there are 3 parts separated by a ., each section is created differently. We have the 3 parts which are:

header
payload
signature
..

Header

The JWT Header declares that the encoded object is a JSON Web Token (JWT) and the JWT is a JWS that is MACed using the HMAC SHA-256 algorithm. For example:

{
“alg”: “HS256”,
“typ”: “JWT”
}
“alg” is a string and specifies the algorithm used to sign the token.

“typ” is a string for the token, defaulted to “JWT”. Specifies that this is a JWT token.

Payload (Claims)

A claim or a payload can be defined as a statement about an entity that contians security information as well as additional meta data about the token itself.

Following are the claim attributes :

iss: The issuer of the token

sub: The subject of the token

aud: The audience of the token

qsh: query string hash

exp: Token expiration time defined in Unix time

nbf: “Not before” time that identifies the time before which the JWT must not be accepted for processing

iat: “Issued at” time, in Unix time, at which the token was issued

jti: JWT ID claim provides a unique identifier for the JWT

Signature

JSON Web Signatre specification are followed to generate the final signed token. JWT Header, the encoded claim are combined, and an encryption algorithm, such as HMAC SHA-256 is applied. The signatures’s secret key is held by the server so it will be able to verify existing tokens.

JWT-Real world

Advantages of Token Based Approach

JWT approach allows us to make AJAX calls to any server or domain. Since the HTTP header is used to transmit the user information.

Their is no need for having a separate session store on the server. JWT itself conveys the entire information.

Server Side reduces to just an API and static assets(HTML, CSS, JS) can be served via a CDN.

The authentication system is mobile ready, the token can be generated on any device.

Since we have eliminated the need for cookies, we no more need to protect against the cross site requesets.

API Keys provide either-or solution, whereas JWT provide much granular control, which can be inspected for any debugging purpose.

API Keys depend on a central storage and a service. JWT can be self-issued or an external service can issue it with allowed scopes and expiration.

You can use jwt in node.js, angular.js, ruby, Java, .net and other frameworks.
Following is example of JWT generator and verify jwt token

Generate Tokens

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import io.jsonwebtoken.*;
import java.util.Date;    

//Sample method to construct a JWT

private String createJWT(String id, String issuer, String subject, long ttlMillis) {

//The JWT signature algorithm we will be using to sign the token
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);

//We will sign our JWT with our ApiKey secret
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey.getSecret());
Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

  //Let's set the JWT Claims
JwtBuilder builder = Jwts.builder().setId(id)
                                .setIssuedAt(now)
                                .setSubject(subject)
                                .setIssuer(issuer)
                                .signWith(signatureAlgorithm, signingKey);

 //if it has been specified, let's add the expiration
if (ttlMillis >= 0) {
    long expMillis = nowMillis + ttlMillis;
    Date exp = new Date(expMillis);
    builder.setExpiration(exp);
}

 //Builds the JWT and serializes it to a compact, URL-safe string
return builder.compact();
}

Decode and Verify Tokens

import javax.xml.bind.DatatypeConverter;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.Claims;

//Sample method to validate and read the JWT
private void parseJWT(String jwt) {
//This line will throw an exception if it is not a signed JWS (as expected)
Claims claims = Jwts.parser()         
   .setSigningKey(DatatypeConverter.parseBase64Binary(apiKey.getSecret()))
   .parseClaimsJws(jwt).getBody();
System.out.println("ID: " + claims.getId());
System.out.println("Subject: " + claims.getSubject());
System.out.println("Issuer: " + claims.getIssuer());
System.out.println("Expiration: " + claims.getExpiration());
}

Happy secure API call with Vinay in techartifact . 🙂

– See more at:
http://blog.apcelent.com/json-web-token-tutorial-example-python.html#sthash.GzZriR3U.dpuf
http://angular-tips.com/blog/2014/05/json-web-tokens-introduction/

How to Create and verify JWTs in Java

Vinay

I am an Oracle ACE in Oracle ADF/Webcenter. Sr Java Consultant-working on Java/J2EE/Oracle ADF/Webcenter Portal/ content and Hibernate for several years. I'm an active member of the OTN JDeveloper/Webcenter forum. Passionate about learning new technologies. I am here to share my knowledge. Give your views and suggestion on [email protected] .

More Posts - Website

Follow Me:
TwitterLinkedInGoogle PlusYouTube