Skip to main content

Deep Dive into Json Web Tokens (JWT)

Β· 5 min read

What is JWT?​

JSON Web Token (JWT) is an open standard that defines a compact and self-contained way to securely transfer information as JSON objects between parties.

Usage scenarios of JWT​

Here are some situations where JWT is used:

Authorization: This is the most common scenario for using JWT. After the user logs in, each subsequent request will contain the JWT, allowing the user to access the routes, services, and resources that the token allows.

Information exchange: JWT is a good way to transfer information securely between parties. Because the JWT can be signed (for example, using a public/private key pair), you can be sure the sender is a trusted person and verify that the content has not been tampered with.

Data structure of JWT​

JWT consists of three parts separated by "dots" (.), which are:

  • Header
  • Payload
  • Signature

Therefore, JWT is usually as follows

xxxxx.yyyyy.zzzzz;

The Header usually consists of two parts: the type of token (that is, JWT) and the signature algorithm used, such as HMAC SHA256 (HS256) or RSA. For example,

{
"alg": "HS256", // algorithm
"typ": "JWT" // token type
}

Payload​

The second part of a token is Payload, which contains claims. Declarations are declarations about entities (usually users) and other data.

There are three types of declarations:

  • Registered Claims : A set of predefined declarations that are not mandatory but recommended.

    • The Issuer of iss (Issuer);
    • sub (Subject) Subject;
    • aud (Audience);
    • exp (Expiration Time) Expiration Time;
    • nbf (Not Before) effective time;
    • iat (Issued At) issue time;
    • jti (JWT ID) number;
  • Public claims : A declaration that can be arbitrarily defined by someone using JWT.

  • Private Claims : Custom statements are intended to share information between parties that agree to use them and are neither registration statements nor public statements.

For example:

{
"sub": "1234567890", // Registered claims
"name": "John Doe", // Private claims
"admin": true // Private claims
}

Note that for signed tokens, this information, while tamper-proof, can be read by anyone. Do not put confidential information in the Payload or Header element of the JWT unless it is encrypted.

Signature​

The Signature part is the Signature of the first two parts of the token to prevent data tampering.

First, you need to specify a secret. This key is known only to the server and cannot be disclosed to users. Then, using the signature algorithm specified in the Header (HMAC SHA256 by default), generate the signature as follows.

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

Combination​

After calculating the Signature, you can combine the Header, Payload, and Signature serialized by the Base64-URL algorithm into a long string, and separate each part with dots (.). This string can be easily transmitted in HTML and HTTP environments.

The following figure shows a JWT that has encoded the previous Header and Payload and signed with a secret.

Combination

If you want to use JWT and put these concepts into practice, you can use the jwt. IO Debugger to decode, validate, and generate JWT.

image

The way JWT works​

In authentication, JWT is returned when the user successfully logs in with his credentials. Because the token is used as a credential, extra care must be taken to prevent security issues. In general, JWT retention should not exceed the required time.

You should also not store sensitive session data in the browser's storage due to lack of security.

Whenever a user wants to access a protected route or resource, the user agent should send the JWT, usually by choosing the Authorization field hosted in the Request Headers. As follows:

Authorization: Bearer <token>

In some cases, this can be a stateless authorization mechanism. The server's protected route checks for valid JWT in the Authorization field and, if present, allows users to access the protected resource. If the JWT contains the necessary data, you can reduce the need to query the database for certain operations.

If tokens are sent in Authorization, cross-domain resource sharing (CORS) is not a problem because it does not use cookies.

The following figure shows how to take JWT and use it to access an API or resource:

how-to-community-with-jwt

  • The application or client requests authorization from the authorization server.
  • After authorization is granted, the authorization server returns the token to the application.
  • Applications use this token to access protected resources (such as apis).

Summary​

  • JWT is not encrypted by default, but it can be encrypted. Once the original Token is generated, it can be encrypted again with the key.

  • JWT The secret data cannot be written into the JWT without encryption.

  • JWT can be used not only for authentication, but also for information exchange. Using JWT effectively can reduce the number of times the server queries the database.

  • The biggest disadvantage of JWT is that the server does not store the session state, so you cannot revoke a token or change the permission of the token during use. That is, once a JWT is issued, it remains valid until expiration, unless the server deploys additional logic.

  • JWT itself contains authentication information, and if it is disclosed, anyone can gain full access to the token. To reduce theft, JWT expiration dates should be shorter. For some important permissions, the user should be authenticated again.

  • To reduce the probability of theft, JWT should use HTTPS instead of HTTP.