Signature

The third part of the token is the signature, which is a signed version of the previous two elements. This is shown as follows:

HMACSHA256(base64UrlEncode(header)+"."+base64urlEncode(payload), secret)

Here, we create an HMACSHA256 signed token. We use the base64UrlEncoding of the header, followed by a period, then a base64UrlEncode of the payload, which is the collection of the claims and an HMAC secret.

Depending on the algorithm used, this step of signing the token may vary. However, the idea here is to encode and sign the token with a secret. This becomes the third part of the JWT token.

So, our JWT token is in a format like this:

Base64UrlEncode(header).base64Encode(payload).HMACSHA256(base64UrlEncode(header)+"."+base64urlEncode(payload), secret)

An example value of the JWT is shown as follows:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.eyJzdWIiOiJ0ZXN0dXNlcmlkIiwibmFtZSI6IlRlc3QgVXNlciIsImlhdCI6MTUzNDkzNzQ0OH0
._mPNoWWCq3dYjN7cU3lemI23Ft_uEyA9woY_dJpu9l0

Note that the three parts of the token are separated by the period (.) character. The JWT of this sort will be passed in the request while making a call to the resource on the server. This JWT token can be passed as an authorization header, as a Bearer token, or a query parameter; whichever form that the server's resource can understand.

One final note about the JWT is that the claims that we use, such as aud, iat, exp, and  sub, are registered with the IANA (https://www.iana.org/assignments/jwt/jwt.xhtml), the organization that manages these sorts of names used when generating the JWT token information. We can register the new name with the IANA. But this already has a set of reusable claims that are sufficient for the web/REST resource authentication and authorization.

As we have seen, a JWT is a compact, stateless, digitally signed token that we can use for authentication and authorization mechanisms.

We will implement a simple example of generating a JWT and validating it to see how to protect a REST endpoint using JWT.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset