JSON Web Tokens (JWT)

Overview

JSON Web Tokens is an emerging standard. They are very close to their standardisation. IETF has taken care of that, and OpenID connect mandates the use of JSON Web token for all of the tokens that are exchanged in that protocol. this article gives you a little look, an overview of the purpose of security tokens, and, and what other types of tokens we have out there and where, where they are used. Then we have a look at the structure of a JSON Web Token, and then we’ll show you how easy it is to create and consume them using the Microsoft DotNet Core development framework.

The Purpose of Security Tokens

The purpose of a security token is really to produce a data structure that contains information about the issuer and about maybe the recipient and about the subject that this token describes. Think of an authentication operation where you sign in somewhere, and the authentication server sends back to the application a token that defines your identity, holding all the information about you and your session. Obviously must be protected so nobody can tamper with that and change its contents. So these tokens are also signed.

Depending on the technology, you either sign them symmetrically or asymmetrically and signing moreover fulfils the need or the purpose of making them authentic, meaning the recipient of that token wants to make sure it is coming from a trusted source.

When you trust the issuer of the token, you can also trust the contents of the token, and the claims which are typically inside of the token.

Tokens usually contain an expiration time, so you know, they only have a limited validity Depending on the scenario, this might be something like a workday. Or maybe with access tokens, they are very short-lived, like an hour or even shorter.

So tokens are very important, they are critical aspects to all of the protocols in the security space. Thus, a client which is an application, requests the token, an issuer issues a token and a resource consumes a token.

JWT Structure and Format

JWT is on its way to official standardisation

So how does the JSON Web Token look like? It basically has two parts one is the header which provides some metadata and some information about which algorithms and which keys are used for, for doing the cryptographic operations, and it has a number of it has claims just generally speaking.

Header

  • metadata
  • algorithms & keys used

Claims

  • Issuer(iss)
  • Audience(aud)
  • IssuedAt(iat)
  • Expriation(exp)
  • Subject(sub)
  • ..and application defended claims

There are claims fall into two areas one is reserved claims. Some of them you see here on the slide, and then you can have application-defined claims that you can freely define.

Essential a token has at least an issuer claim, so the recipient knows where the token is coming from. It has an audience claim, so the recipient knows that he is the right recipient for the token and not someone else.

Here they typically have an IssuedAt claim, which tells the recipient when the token was issued, an Expiration claim relating the recipient when the token has expired, and the Subject claim, which is basically like an identifier of the entity that this token describes, like a UserID for example.

Header
{
"alg": "HS256",
"typ": "JWT"
}

Claims
{
"iss": "abc",
"unique_name": "2",
"nbf": 1590849115,
"exp": 1590849175,
"iat": 1590849115,

"client": "acme",
"scope": ["read", "search"]
}

The structure of a sample JSON Web Token. You can see on top we have the header section. The algorithm says here that we are using an HMAC SHA-256 to assign the token.

Now in the claims section, you see some of the claims. The expiration is an epoch time. Meaning you’re taking the number of seconds from the first January of 1970. So that’s the way they get around all the different date-time encodings on cross-platform.

Producing and Consuming JWTs

So how would you produce a token?

A very good and simple working example of JWT in action is produced by Jason Watmore:

https://github.com/cornflourblue/aspnet-core-3-jwt-authentication-api

A Microsoft library on NuGet that implements JSON Web Token handling. It has a classes called JSON Web Token, SecurityToken, or JWTSecurityToken. And you pass in the claims that we talked about earlier, so like the Issuer claim, the Audience claims that describe the subject.

var token = new JWTSecurityToken(
     issuer: "http://myIssuer",
     audience: "http://myResource",
     claims: GetClaims(),
     signingCredentials: GetKey(),
     validFrom: DateTime.UtcNow,
     validTo: DateTime.UtcNow.AddHours(1));

// serialize
var tokenString =
new JWTSecurityTokenHandler().WriteToken(token);

You tell the class what’s the signing credential, and you tell them that the validFrom, validTo thing. And then you can use a class called the JWTSecurityTokenHandler to serialise the token. Then you can just transmit that via arbitrary means. You could put on a header in an HTTP request, you could put it in the query string , you could even put it into a cookie. It doesn’t matter it’s just a string, that you can pass around in your system in a very flexible way.

Now the consumer of that token, the most common thing obviously, would be in the HTTP header. To validate a token, you just read that string, you put it back into this short security token class. You set some validation parameters, for example

var token = new JWTSecurityToken(tokenString);
var validationParams = new TokenValidationParameters
{
     ValidIssuer = "http://myIssuer",
     AllowedAudience = "http://myResource",
     SigningToken = GetSigningKey()
};

var handler = new JWTSecurityTokenHandler();
var principal = handler.ValidateToken(token, validationParams);

The issuer to be my issuer, your audience to be myResource, and that is the signing key that you use to validate the signature.

It’s that easy, there are libraries for all platforms like Java and PHP and, and Node and so on, that can deal with JSON Web Tokens.