DEV Community

Leo Kalshteyn
Leo Kalshteyn

Posted on

Intro to JSON Web Tokens

There are different ways to implement authentication for web apps and one of them is through something called JSON Web tokens or JWT. JWT is a standard that defines a compact and self-contained way to securely transmit information between a client and a server as a JSON object. The compact size makes the tokens easy to transfer through an URL, POST parameter, or inside an HTTP header. Information in a JWT is digitally signed using key pairs as well.

JWT are primarily used for authentication. After a user logs in to an application, the application will create a JWT and send it back to the user. Subsequent requests by the user will include the JWT. The token informs the server what routes and resources the user has access to.

JWTs consist of three parts with dots in between:

  • Header
  • Payload
  • Signature

An example would look like:

euwuad17wbu90bwbdau.rggiri325rngnsg.53diwiwniwoqoq40489

Header

The header typically consists of two parts: the type of the token, which is JWT, and the hashing algorithm such as HMAC SHA256 or RSA.

For example:

{
  "alg": "HS256",
  "typ": "JWT"
}
Enter fullscreen mode Exit fullscreen mode

Then, this JSON is Base64Url encoded to form the first part of the JWT.

Payload

The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the user) and additional metadata. There are three types of claims: reserved, public, and private claims.

Reserved claims: These are a set of predefined claims, which are not mandatory but recommended, thought to provide a set of useful, interoperable claims. Some of them are: iss (issuer), exp (expiration time), sub (subject), aud (audience), among others.

Public claims: These can be defined at will by those using JWTs. But to avoid collisions they should be defined in the IANA JSON Web Token Registry or be defined as a URI that contains a collision resistant namespace.

Private claims: These are the custom claims created to share information between parties that agree on using them.
An example of payload could be:

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}
Enter fullscreen mode Exit fullscreen mode

Signature

The signature consists of the encoded header, the encoded payload, a secret, the algorithm specified in the header, and the signing of that. It is used to verify the sender of the JWT and to ensure the message wasn't changed

Example with the HMAC SHA256 algorithm.

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)
Enter fullscreen mode Exit fullscreen mode

A good diagram of how JWT works:

Alt Text

Check out Link to read more about it and where you can test out as well as decode, verify and generate JWT.

References

Discussion (0)