Skip to content

JSON Web Tokens (JWT)

Adarsh Kumar Maurya edited this page Dec 5, 2018 · 2 revisions

Overview

Let's start with a quick look at JSON web token. As I said, JSON Web Tokens are an emerging standard. They are very close to its 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. And OAF two, isn't mandated, but as I said most implementations these days use JSON Web Token.

So let's have a look at them first. So, I want to give you a little 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 I want to quickly show you how easy it is to create and consume them using development framework.

The Purpose of Security Tokens

So 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.

So think of an authentication operation where you sign in somewhere and the authentication server sends back to the application a token that describes your identity. And that obviously must be protected so nobody can tamper with that and change its contents. So this tokens are in addition typically signed. Depending on the technology you either sign them symmetrically or asymmetrically. And signing also fulfils the, the, 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. Because only when you trust the issuer of the token you can also trust the contents of the token the, the claims typically that that are in, inside of the token.

Tokens typically contain an expiration time, so you know, they only have a limited validity depending on the scenario, this might be something like a work day, like ten hour, for example in that's very common in SAML for example. Or maybe with Access tokens, they are very short-lived like something like, like an hour or even shorter to minimize the window well, like for example a stolen token could be abused. So tokens are very, very important, they are key aspects to all of, all of the protocols in the security space.

So a client, which is an application, requests the token, an issuer issues a token and a resource consumes a token.

And obviously, a, as I said earlier, the resource, typically some web API, has a trust relationship with the issuer of the token, meaning they had some a priori key exchange. So, the consumer knows about the key that the, the issuer uses for signing the token and can use that key to validate the token and if that validation succeeds the resource can use the claims inside of the token.

History

There are historically a number of tokens that we were using. The one that's not on this slide is a Kerberos service ticket. I skipped that here, but strictly speaking also in Kerberos we have pass around security tokens.

But the term security token became much more popular in WS star or SAML space. So, the most the most popular and most widely used security token today, is certainly the SAML(Security Assertion Markup Language) token, the security assertion markup language token, there are two flavors to version 1.1, and version 2.0. They are XML based and they have many, many options on how you can encrypt them and sign them and they're very expressive. And, you need typically a pretty advanced XML stack to be able to parse and produce them because it's not only XML there's also schema involved there is XML encryption involved, which is a pretty complicated standard. There is XML digital signatures involved and so on.

So in the area where you had all this powerful a SOAP(Simple Object Access Protocol) and XML engine, like in WCF for example. These are very, very popular tokens. Now, as I said earlier and in the last module these newer devices, like mobile devices for example, they don't really have these advanced XML stacks anymore.

So, one token type that was created as a direct, you know, reaction to making SAML much, much more simpler was the SWT Simple Web Token. This was a joined venture by Microsoft, Google, and Yahoo. And they took a very simple approach. They basically used key value pairs for claims, form URL encoded them, and only provided as a part for symmetric signatures.

Now, it turned out that these tokens were a little too simple, so we need a little bit more of the SAML features. And we need a little bit more cryptographic options because symmetric signatures they just don't scale very well once the systems become more, more complicated.

So, from taking the experience of SAML, what is good about SAML, and what was missing in the Simple Web Tokens. There was the idea that came up with the JSON Web Token or the JWT as many say. And the JSON Web Token, the idea is that you are encoding the token using JSON and that that's very beneficial because you will find that JSON path on, on almost every platform and even if there is no path it's really simple to pass them. You could pass them manually by hand that wouldn't be too hard. But also I guess, one of the big features is that since JSON is the native format in in JavaScript, and JavaScript becomes a much more important language these days it's also very easy to use from JavaScript, which is a plus for many people. The next thing is they agreed on a number of cryptographic algorithms that can be used for signing and for encryption. Not as many as you could use in SAML because that is really an open model here. But you know some that make sense and there is HMAC SHA for symmetric signatures and elliptic curves and RSA for asymmetric signatures. And we have RSA and AES CGM which is an authenticated encryption algorithm to do encryption. So it's less complicated than SAML, but more advanced than Simple Web Tokens and that it seems to hit the sweet spot for many people, so just became pretty quickly, quickly the standard token type to use for many of these interactions and that's what we are going to use here as well.

JWT Structure and Format

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.

There is claims fall into two areas one are reserved claims. That some of them you are seeing here below and then you can have application defined claims that you can freely define.

                JSON Web Token

* On its way to official standardisation
 - [https://tools.ietf.org/html/rfc7519](https://tools.ietf.org/html/rfc7519)

* Header
 - metadata
 - algorithms and keys used

* Claims
 - Issuer(iss)
 - Audience(aud)
 - IssuedAt(iat)
 - Expiration(exp)
 - Subject(sub)
 - ... and application defined claims

But really important tokenJWT token basically at least have 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 really 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 telling 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.

And you, and you see also that they're using abbreviations like iss for Issuer or Audience- aud for Audience. So, another intent of this JSON Web Token format is to keep these token sizes really small, so you can use them in mobile scenarios very well.

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

Claims {
        "iss" : "http://myIssuer",
        "exp" : "1340819380",
        "aud" : "http://myResource",
        "sub" : "alice",
        "client" : "xyz",
        "scope" : ["read", "search"]
       }

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC8xOTIuMTY4LjAuNDo4MDAwXC9hcGlcL3YxXC91c2VyXC9zaWduaW4iLCJpYXQiOjE1NDM5NjU4NDQsImV4cCI6MTU0Mzk2OTQ0NCwibmJmIjoxNTQzOTY1ODQ0LCJqdGkiOiJQb21zeUpzRDFuMXlRYm9mIiwic3ViIjo5LCJwcnYiOiI4N2UwYWYxZWY5ZmQxNTgxMmZkZWM5NzE1M2ExNGUwYjA0NzU0NmFhIn0.j3hglMpJFo0aFNpM7Am8xdCUyV85vDd1PccOIRMLh-g

Header.Claims.Signature

This is the structure of a sample JSON Web Token.You can see on top we have the header section. So you see that it's a chart, so that can be used for versioning.And 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 I just talked about like the issuer, the expiration that's epoch time by the way. 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. You have the audience. You have the sub check alice in this case.Then we have a claim called client, so that could be useful for example, in OAF when you want to know which application requested that token. And you have something called scopes which also again is something which is useful in OAF to do authorization, as we will see later in the OAF module.

But as I said you can put in whatever claims you want here. And then we have a way to serialize that token and as you can see at the bottom, you basically take the header part Base64 URL encoded, we'll take the claims part Base64 URL encode. And then you'll take this string with the dot in the middle and you run the signature algorithm, over that string and depend the Base64 URL encoded signature at the end with a dot. And that's how you transmit JSON Web Tokens. So that's quite simple especially if you compare that to how SAML tokens work.

Producing and Consuming JWTs

So how would you produce a token? I will point you to more libraries in, in the appendix, but if you are a .NET developer the most obvious one you would use is, is the one from Microsoft. So there's a Microsoft library on NuGet that implements JSON Web Token handling.

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

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

And as you can see, there a class called JSON Web Token, SecurityToken, or JWTSecurityToken. And you pass in the claims that I talked about earlier, so like the Issuer claim, the Audience claim, claims that describe the subject. You tell the class what's the signing credential, you tell them that the validFrom, validTo thing. And then you can use a class called the JWTSecurityTokenHandler to serialize the token. And then you can just transmit that via arbitrary means. Yeah?

So. You could put on a header in an HTTP request, you could put it on the, in the query string you know, you could even put it in, into a cookie. It doesn't really matter. It's, it's just a string now, that you can pass around in your system in a very flexible way.

Now the consumer of that token, he would just you know retrieve that serialised last string, as I said from wherever you put it on. The most common thing obviously, would be in the HTTP header. And to validate a token, you basically just read that string, you, you put it back into this short security token class.

You set some validation parameter, for example, I expect the issuer to be myIssuer, I expect your audience to be myResource and that is the signing key that you, that that, the class should use to validate the signature. And then again you can use the, the JWT security JWT in handler class call of elevate a token on that and get back a claims principle containing all the claims in the token and that includes the reserved claims like issuer, audience, expiration, and so on plus the claims describing the subject.

So that is, that is really easy. And there are, in the meantime, there are now libraries for all platforms like Java and PHP and, and Node and so on, that can deal with JSON Web Tokens.

Summary

I want to get that out of the way, so whenever I say token in this in this training here, I always mean JSON Web Tokens, as a data they are the defacto standards that are used by OAuth and OpenID Connect. At least for the, for the more modern implementation.

You see given its format, it's simply a string. It's relatively easy to create transmit pass and validate those JWT tokens. You have good library support. And all of that combined make them the obvious choice these days for, for tokens.

There are other token types out there and I will put some links to them in, into the resources appendix but given the bigger implementations today like Microsoft and, and Google and and these types of companies really the top form of data we can use. And as I said already in OpenID connect they also specify the JWT as, as the only token type they support.

Clone this wiki locally