Skip to content
Home » Blog » Using JSON Web Tokens for Increased Security

Using JSON Web Tokens for Increased Security

  • by

JSON Web Tokens (“JWT”) are a extensively used different to session cookies and different forms of tokens utilized in requests or transactions between events and have been gaining in recognition since their introduction a few years in the past. Recently Iterable added assist for using JSON Web Tokens when authenticating API calls, for elevated safety particularly in a cellular context. Let’s look at intimately what they’re, the place they got here from, and why you would possibly wish to use them in your software.

What are JSON Web Tokens?

JSON Web Tokens (pronounced “jot”) are after all tokens—strings of characters which have sure traits. As you would possibly anticipate by their title, these tokens comprise JSON payloads, but in addition, every JWT carries its personal signature with it.

The JSON payload a part of the token makes sure claims (extra on that later) and the signature half is definitely verifiable and unforgeable. JWTs have been known as moveable models of identification and self-encoded entry tokens. A key property of JWTs is that with a purpose to validate every JWT-containing request, you want solely have a look at the token supplied throughout the request—no must contact a third-party service or maintain the token in reminiscence between requests. This is as a result of they transmit their very own authentication code within the token itself.

A Brief History of JWT

Many years in the past, some devoted researchers acknowledged that since JSON was extensively getting used to move information all through the web, it could be fairly helpful and safer to outline a typical signing mechanism for it. The oldest model of a specification for signed JSON that I discovered on-line was from September 2010 – JSON Simple Sign 1.0 draft 01. One of the authors of that doc listed three authentic targets for this proposal:

  • Encryption Support
  • Algorithm Flexibility
  • Simplicity

This advanced right into a JSON Web Token Internet-Draft (working doc of the IETF) in July of 2011, which was in flip formalized in May 2015 because the open customary outlined within the IETF doc RFC 7519, and has been carried out extensively since then.

JWT in Detail

A JWT is an encoded textual content string which is made up of three elements separated by dots. The three elements are the Header, the Payload, and the Signature, i.e. [Header].[Payload].[Signature].

The Header

The header sometimes consists of JSON specifying the signing algorithm and the token kind, e.g.:

This JSON is then Base64Url encoded to type the primary a part of the JWT.

There are a few issues to notice about this. First, the header is encoded, not encrypted. The goal of encoding strings is to enhance information usability, so encoding algorithms are reversible by anybody, utilizing publicly accessible schemes. Therefore, anybody who accesses your JWT can simply learn the contents of the header. Next, Base64Url is a variant of Base64 encoding that’s protected for use in URLs, since typically JWTs could also be transmitted as parameters in URLs.

The Payload

The payload comprises JSON specifying the claims (fascinating consumer information) which can be a part of this token.

This JSON can be Base64Url encoded to type the second a part of the JWT. There are three forms of claims that may be included within the payload. Registered claims are predefined within the specification and have particular meanings. The dealing with of the non-time-based claims is application-specific. All time-based claims are expressed in seconds because the epoch. Some examples:

  • aud – viewers
  • sub – topic
  • iss – issuer
  • exp – expiration time
  • iat – issued at
  • nbf – not earlier than

Private claims are advert hoc values which can be outlined by the customers (i.e. producers and customers) of the JWT with a purpose to share info, and sometimes comprise figuring out information for the consumer being referenced within the related request.

Public claims are both given collision-resistant names (by way of a namespace prefix) or outlined in a claims registry. Since the payload is encoded and never encrypted, any contained consumer information isn’t confidential and thus no delicate information must be included (particularly passwords!).

The Signature

The signature is used to validate that the info within the JWT has not been tampered with, so the signature doesn’t comprise JSON. Instead, it’s created by taking the encoded header and the encoded payload and a secret password and hashing that utilizing the algorithm that was specified within the header’s JSON.

Two widespread hashing algorithms in JWT are HMAC utilizing SHA-256 (specified as HS256 within the JWT header JSON), and RSASSA PKCS1 v1.5 utilizing SHA-256 (specified as RS256). RS256 offers considerably stronger safety as a result of HS256 makes use of shared secrets and techniques (the identical secret string is used to each signal and validate the JWT), whereas RS256 makes use of a public/non-public key pair (the JWT is signed utilizing the non-public key and validated utilizing the general public key).

Validating the JWT

To validate the JWT, merely extract the primary 2 elements (header plus payload) from the token after which run the suitable hash operate on it, utilizing both the shared secret or the general public key, after which lastly encode that outcome and examine it to the final a part of the token that was handed.

Even if it matches, you aren’t fairly completed but.

You should then validate all of the claims that had been handed within the payload. You ought to examine all of the time-based claims. Has it expired? Is it not legitimate but? Using the issued at declare, you possibly can even calculate the age of the JWT and reject it whether it is too outdated in response to your software’s wants. Finally, it is best to examine any consumer info and ensure that it references a sound consumer of your software.

Why Use JWT?

The following are some properties of JWT that make it a horny token alternative for many programs:

  • Standard-BasedRFC 7519
  • Stateless – Like HTTP, JWT is stateless. It isn’t essential to maintain the tokens in reminiscence between requests.
  • Self-Contained – Since the tokens are self-contained and self-validating, nothing must be saved in a database or seemed up.
  • Good Performance – In follow, JWTs can and are used at web scale since as we’ve got seen above, token parsing and validation are environment friendly operations.
  • Portable – Since JWTs are homogenous and never tied to any specific kind of system, they’re moveable. A single token can be utilized with a number of backends.
  • Mobile Friendly – It isn’t mandatory to make use of cookies when implementing JWT (in the event you choose to retailer the token, you are able to do it nevertheless you need). That, and the opposite above factors, make JWT a good selection for cellular programs.
  • Built-in Token Expiration – Simply specify the exp declare within the payload of the JWT.
  • Easy to Debug – JWTs might be inspected throughout implementation and testing.
  • Decentralized – Your authentication server might be decoupled out of your software server. The consumer can login to your auth server, get a JWT, after which use that to make calls to your software server.

Why You Might Not Want to Use JWT

Not everyone is a JWT fan. Several articles bemoaning using JWT are simply an web search away. Here are some explanation why utilizing JWT may not be applicable for all programs:

  • Reducing Database Lookups is Not Useful – If your system is already hitting the database on each request, decreasing lookups wouldn’t be useful.
  • Larger Tokens – Since they embody a signature, JWT are longer than another forms of tokens and the extra overhead could also be detrimental for some programs.
  • Desire for Opaque Tokens – There are many who really feel that tokens must be used and never examined.
  • Difficult to Revoke – Once a JWT is distributed, it’s tough to unexpectedly revoke it, since you can not simply replace a database desk row. For instance, revoking may be mandatory if the consumer’s account has been suspended.

Examples of Practical Applications

JWTs are used to confirm {that a} consumer is who they are saying they’re, and to grant or deny rights to entry assets.

Some programs use JWTs to Authenticate API Requests. In one widespread situation, the API consumer first offers credentials on a login web page, which returns the JWT as soon as these credentials are validated. The payload within the returned JWT will comprise consumer info, probably consumer permissions, and every other claims which can be vital for the appliance.

Then, that JWT is handed in subsequent API calls because the Authorization: Bearer token (although it can be despatched within the POST physique or as a part of the URL). In the Iterable use case, our clients (builders of a cellular app) generate a JWT for every cellular app consumer, that’s handed to the Iterable Mobile SDK which makes use of the JWT when making API calls to Iterable.

Some programs use JWTs for Authorization. Access to assets and operations might be managed by way of claims within the JWT payload. For instance, administrator entry may be enabled by passing the {“admin”:true} declare.

Single Sign-on (SSO) Systems, which authenticate a single credential throughout a number of programs inside one group, extensively use JWTs as entry tokens. Federated Identity Systems, which provide single entry to many functions throughout a number of enterprises, make use of various kinds of tokens by way of the OAuth 2.0 open customary. Though OAuth 2.0 doesn’t specify a selected token format, JWT is an efficient match for a few of these tokens and certainly many standard platforms use JWT for their OAuth 2.0 tokens. OpenID Connect (OIDC), which is constructed on prime of OAuth 2.0, defines how you can authenticate customers and explicitly specifies JWT for a few of its token elements, the ID token particularly.

In Summary

Since being outlined, JWT has continued to realize in recognition and utilization. It has discovered its method into all main net frameworks, assist for its use is extensively carried out and it’s an integral a part of each OAuth 2.0 and OIDC. If you’re contemplating utilizing JWT for your system, ensure you maintain the next greatest practices in thoughts:

  • Use an Appropriately Strong Hashing Algorithm
  • Always Perform All Validations – signature and payload
  • Pick Strong Keys – lengthy and random
  • Use Different Keys for Different Systems
  • Specify Short Expiration Times – by way of the exp declare

Happy JWT-ing!

Leave a Reply

Your email address will not be published. Required fields are marked *