mug logo
    • Home
    • How-to guides
    • Snippets
    Cheatsheets:LinuxGitBckgrnd

JWT Tokens

December 10, 2020

post-bg

– JWT Tokens
– When to use JWT authentication
– JWT's as session tokens
– JWT API authentication
– How to store JWT's in cookies
Content

JWT - Tokens

A JWT token is a mechanism for verifying the owner of some JSON data. It guarantees a server, that the data can be trusted because it's signed by the source, and it can't be modified once it's sent.
This guarantee; however it's limited to data ownership only; meaning the data stored in it can be seen by anyone that intercepts the token, because it's serialized and not encrypted. For this reason, it's recommended to use HTTPS with JWTs.

When to use JWT authentication

It's particularly useful for API authentication. When a user signs in successfully using his or her credentials, a JSON web token gets returned. The JWT is issued by a third party, and this could be a company such as Okta, Auth0, Azure, GCP, Amazon etc. Once a user is logged in, each subsequent request will include the JWT, thus allowing the user to access routes, services, and whatever else its token would allow him to.

In the authorization header using the Bearer schema.

 Authorization: Bearer <token>

The server then will check for a valid JWT Token in the authorization header before any access to a protected resource is allowed.

JWTs as session tokens

This is not recommended. One issue is that you can't remove JWTs at the end of a session because they're self-contained and there's no central authority to invalidate them. Also, they're relatively large, at the same time, there's a high cost involved since they're sent to the server with each request. Therefore, it's recommended to use regular sessions instead.

API Authentication

The most common use for JWTs is as an API authentication mechanism. It's what Google uses to authenticate to its APIs. When you register for an API service account, you'll get a secret token - often available within the API dashboard. Then this unique identifier is passed as part of the API request to the server.

Storing JWTs in a cookie

JWTs need to be stored in a safe place inside of a user's browser. If you store it in localStorage, it'll be accessible by any script in the page. Therefore, whatever you do, do not store them in localStorage (or session storage).
To keep them secure, you should always store JWTs inside an httpOnly cookie. This is a special type of cookie, that's only sent in HTTP requests to the server.

An HttpOnly Cookie is a tag added to a browser cookie that prevents client-side scripts from accessing the data.

In SPA, JWTs can be used as an authentication mechanism whenever a database isn't required.

post-bg


  • Terms & Conditions
  • kcosa.com © 2025
  • Privacy Policy