Monday, March 21, 2022

JWT Tokens

JWT tokens were created as a way to safely transfer small pieces of data as a JSON object. It's intended to be used to authenticate HTTP requests without sessions. Relying on sessions means utilizing HTTP cookies as a way to validate whether two requests came from the same browser.

JWT can be fully encrypted or simply signed. We'll quickly discuss how signed tokens work.

There are 3 parts to a signed JWT token:

  1. header
  2. payload
  3. secret

The header typically contains at least 2 fields: type and alg (a signing algorithm). Payload contains claims, which is data specific to the user (ie. things like their full name, whether she is an admin, etc). There are 3 types of claims: registered, public and private. We'll skip over these details for this post.

To create a token, we must encode our header and payload as Base64Url (a reversible encoding), then add the secret. The final output are 3 strings separated by a dot (xxxx.yyyy.zzzz) which can later be parsed in the respective environment (ie. the browser).

On a RESTful web server, routes can be protected as follows:

  1. client requests authorization using some sort of standard like OpenID, etc.
  2. under whatever condition (ie. the correct credentials), the server grants authorization
  3. server returns a JWT token
  4. client stores token (outside the scope of this post)
  5. client submits the token inside subsequent HTTP user agent authorization header using the Bearer schema to access protected resources

Keep in mind is that tokens are sensitive. Therefore, don't keep it cached by the client longer then required. Also, don't store sensitive data in the token as there's a lack of security in the browser.

No comments:

Post a Comment

JWT Tokens

JWT tokens were created as a way to safely transfer small pieces of data as a JSON object. It's intended to be used to authenticate HTTP...