Understanding JWT Tokens: How They Work and Why They're Important

By hientd, at: Feb. 25, 2023, 9:50 p.m.

Estimated Reading Time: 14 min read

JWT Token
JWT Token

We will cover some important topics

  1. Introduction to JWT Tokens
  2. How JWT Tokens Work
  3. Advantages of JWT Tokens
  4. Disadvantages of JWT Tokens
  5. Best Practices for Using JWT Tokens
  6. Applications of JWT Tokens
  7. References

Lets go through one by one

1. Introduction to JWT Tokens

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

JWT Tokens are important because they provide a secure and efficient way to handle user authentication and authorization in web applications. JWT Tokens eliminate the need for a server-side session store, which simplifies the architecture of web applications and improves scalability.

JWT Tokens are used in a variety of web applications and architectures, including single-page applications (SPAs), microservices, and APIs. They are commonly used in modern web frameworks such as Node.js, Ruby on Rails, and Django.


2. How JWT Tokens Work

Structure of JWT Tokens

In its compact form, JSON Web Tokens consist of three parts separated by dots (.), which are:

  • Header
  • Payload
  • Signature

Therefore, a JWT typically looks like the following.

xxxxx.yyyyy.zzzzz

Let's break down the different parts.

Header

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

For example:

{
  "alg": "HS256",
  "typ": "JWT"
}
 

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 data. There are three types of claims: registeredpublic, and private claims.

  • Registered claims:
    Registered claims are claims that are associated with a token holder and are used to authenticate their identity. These claims are generated when a token is created and can be linked to a specific user or entity, allowing them to prove their identity and authorise certain activities. Examples of registered claims include a username, email address, and other personal information. Other examples of registered claims include specific access rights and privileges, such as being allowed to view or edit certain data or files, access certain services, or even participate in certain events. Registered claims are an important part of digital identity and token generation, as they allow for secure authentication and verification of users within the system.

  • Public claims:
    Public claims are the statements made by a project about its intentions for the token, such as its purpose, underlying technology, and how it plans to use the funds raised. Some examples of public claims include a project’s pledge to use the funds raised to develop a new product, a promise to use the funds to research a new technology, or a commitment to use the funds to expand its market reach. As public claims form an important part of the token sale process, they must be verifiable and accurate.
    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:
    Private claims are those which are not registered by IANA, and are used to pass additional information that is meaningful only to the parties involved. Private claims can be used to store information such as user preferences, user roles, organization details, and authentication data.
    For example, when a user is authenticated by an identity provider, a JWT may contain a private claim that stores the user's role within the organization (e.g., "admin", "member", etc.). Another example is a private claim that stores user preferences, such as the preferred language or the timezone. Private claims can also be used to store authentication data, such as a one-time token or a timestamp. These claims can then be used by the application to ensure that the user is authenticated and authorized to access the application.

An example payload could be:

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

The payload is then Base64Url encoded to form the second part of the JSON Web Token.

Signature

To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.

For example if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:

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

The signature is used to verify the message wasn't changed along the way, and, in the case of tokens signed with a private key, it can also verify that the sender of the JWT is who it says it is.

If you want to play with JWT and put these concepts into practice, you can use jwt.io Debugger to decode, verify, and generate JWTs.

Token Signing and Verification: 

Token signing and verification in JWT is an authentication process used to ensure that a JSON Web Token (JWT) has not been modified in transit. A JWT is an encrypted piece of data that is used to prove the identity of a user or the authenticity of a request. The JWT consists of three parts: a header, a payload, and a signature. The header and payload are encrypted and then a signature is added to the JWT to make sure that it has not been modified in any way.

When a JWT is sent from a client to a server, the server must verify that the JWT has a valid signature. This is done by using a secret key that is known to both the server and the client. The server then uses the secret key to generate a signature that matches the signature included in the JWT. If the signatures match, then the JWT is verified and the server can trust the data in the payload.

This process of verifying the signature of a JWT is known as token signing and verification in JWT. It is an essential part of authenticating and verifying requests and ensuring that data has not been tampered with. By using token signing and verification, developers can ensure that their applications are secure and that

Storing and Transmitting JWT Tokens:

When storing and transmitting JWT tokens, it is important to consider the security implications. JWT tokens should be stored securely, and not in plaintext. It is also important to consider how the tokens will be transmitted, and to only transmit them over an encrypted connection such as HTTPS. Additionally, JWT tokens should not be stored in a browser, or in a cookie, as this can lead to security vulnerabilities. Instead, the JWT token should be stored in a server-side session, or in a database.

It is also important to consider how long the tokens should be valid for, and to use a secure algorithm for signing and verifying the token. Additionally, JWT tokens should be rotated periodically, to ensure that an attacker cannot use an old, expired token.

Finally, it is important to consider the impact that a lost or stolen JWT token can have. The best way to protect against this is to use short-lived tokens, and to revoke all

3. Advantages of JWT Tokens

Stateless Authentication: JWT Tokens allow for stateless authentication, meaning that the server does not need to maintain session information for each user. This can improve the performance and scalability of web applications.

Scalability: JWT Tokens can help to improve the scalability of web applications, especially in microservices architecture. They allow for the separation of concerns between authentication and authorization, which can make it easier to scale individual services.

Reduced Database Queries: JWT Tokens can help to reduce the number of database queries required for authentication, which can improve performance. This is because the Token contains all the necessary information for authentication, eliminating the need for the server to query a database for user information.

Flexibility: JWT Tokens can be used in a variety of scenarios and can be customized to meet the needs of different applications. They can be used for user authentication and authorization, as well as for securely transmitting data between services.


4. Disadvantages of JWT Tokens

Token Expiration Issues: One of the main disadvantages of JWT Tokens is that once they are issued, their expiration time cannot be changed. This means that if a Token has a long expiration time and a user's privileges or access rights change, the user will still have access until the Token expires. On the other hand, if the expiration time is set too short, the user may need to log in frequently, which can be inconvenient.

Token Security Risks:

1. Insufficient Entropy: JWT tokens are generated using a secret key. If this key is too weak, it can be guessed by attackers and used to create counterfeit tokens. This is why it is important to use a strong key that has enough entropy and is kept secret.

2. Unsigned Tokens: By default, JWT tokens are signed using a cryptographic algorithm. If the token is not signed, it can be easily tampered with by attackers. This is why it is important to always sign tokens using a strong algorithm such as HS256.

3. Unencrypted Tokens: By default, JWT tokens are not encrypted. This means that the payload of the token can be read by anyone who has access to the token. It is important to always encrypt JWT tokens to protect the payload from

Token Size: JWT Tokens can become quite large, especially if they contain a lot of data. This can result in increased network traffic and slower performance. In some cases, it may be necessary to split the Token into multiple parts or use a different authentication mechanism altogether.


5. Best Practices for Using JWT Tokens

Use a Strong Secret Key: The secret key used for signing and verifying JWT Tokens should be long, complex, and kept secret. It is recommended to use a random string generator to create a strong key.

Set Reasonable Token Expiration Time: Set the expiration time of the token to a reasonable length, taking into account the user's needs and the security requirements of the application. Shorter expiration times can improve security, while longer times can improve usability.

Always Use HTTPS: JWT Tokens should always be transmitted over HTTPS, as it provides end-to-end encryption and protects against man-in-the-middle attacks.

Don't Store Sensitive Information in the Token: JWT Tokens should not contain sensitive information, such as passwords or credit card numbers. Instead, store this information on the server side and only include a reference to it in the Token if necessary.


6. Applications of JWT Tokens

User Authentication: JWT Tokens can be used to authenticate users, allowing them to securely access resources and services in a web or mobile application.

Authorization and Access Control: JWT Tokens can also be used for authorization and access control. Once a user has been authenticated, the Token can contain information about the user's permissions and access rights. This information can then be used to control access to specific resources or services within the application.

Improved API Security: JWT Tokens can be used to secure APIs by authenticating and authorizing requests made to the API. This helps prevent unauthorized access and helps protect sensitive data.

Session management: JWT tokens can be used to manage user sessions. The token can be stored on the client-side and sent along with each request to the server. This allows the server to easily keep track of which user is making which request. This is especially important


7. References

JWT.io: https://jwt.io/
Microsoft Docs: https://learn.microsoft.com/en-us/azure/active-directory/develop/access-tokens
Auth0.com: https://auth0.com/learn/json-web-tokens


Related

Python Unit Test

How To Write Unit Test - Advanced

Read more
Python

Common Python Problems

Read more
Python

The Best Python Blogs

Read more
Subscribe

Subscribe to our newsletter and never miss out lastest news.