Using JWT? You need avoid these implementation mistakes (2024)

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. JWT are widely used in authentication, authorization and information exchange. Among these use cases, the most common scenario for using JWT is for authorization purpose. Once a user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. You may start to ask why not using Session token. One reason is that the JWT is stateless compared with Session tokens, it means that the server side does not have to store the JWT in a centralized DB to perform the validation when a clients sends a request to the server, whereas, the server has to store the session cookies for validation purpose.

To understand the common implementation mistakes of JWT, we need first figure out the structure of the JWT token as most the implementation errors are caused by misunderstanding the structure of JWT token and how each component of JWT are used for.

Structure of JWT Token

A well-formed JWT consists of three concatenated Base64url-encoded strings, separated by dots (.):

  • Header : contains metadata about the type of token and the cryptographic algorithms used to secure its contents. For example
{ "alg": "HS256", "typ": "JWT", "kid": "path/value" //optional}
  • Payload : contains verifiable security statements, such as the identity of the user and the permissions they are allowed. An example of the payload could be
{ "username": "test@example.com", "id": "new user"}
  • Signature : it is used to validate that the token is trustworthy and has not been tampered with. When you use a JWT. Signature is piece of encrypted data of the Header and Payload date by using certain encryption method (such as HMAC,SHA256) with a secret which should be residing on a server side.
HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)

After putting all them together, a JWT looks like

Common Implementation Error

JWT itself is considered as secure method. Most of the security issues discovered against JWT are caused by implementation mistakes.

Leak the secret key

JWT is created with a secret keyand that secret key is private to you which means you will never reveal that to the public or inject inside the JWT token. However, sometimes, the developers could mistakenly leak the signing secret to public. For example, the JWT signing secret is stored on a client side javascript functions or stored on a public accessible files. As a consequence, an attacker could bypass the signature verification easily as the attacker could sign any payloads with the secret to put the server side signature validation in vain. Here is one example listed under Hackerone where the developers are adding hardcoded secret in the client side javascript file.

Using Predictable secret key

It is also possible that the developers are copying a piece of code from a sample code base when implementing the JWT on the server side or they are using a simple word (not randomly generated complex string) as the secret value when implementing the JWT on the server side . A brute force attack could easily extract the secret key as the attacker knows the algorithm, the payload with the original information and the resulting signature of the encrypted payload and header. One example listed under Hackerone shows how a developer is using the ‘secret’ as the secret when implementing the JWT on the server side.

Broken JWT Validation

There are numerous way how the JWT validation could be broken during insecure implementation. Here are some typical examples where a broken JWT validation could happen.

  • Not Validate Signature at all. Some developers implement the JWT validation in a wrong way, where they only decode the JWT payload part without validating the signature part before accepting the JWT as a valid token.
  • Not Validate the JWT correctly if None alg is provided. An attacker could or creates a token by settingalg(the signing algorithm) toNonein the header. If the server side is NOT validating whether the None alg was really implemented when the JWT was generated. As a consequence, any JWT provided by the attacker with a None value to the alg will be treated as a valid token. To prevent this, the server side should check whether the alg value is the one when the JWT token is generated. If not, the JWT should be treated as an invalid.
  • Not Validate the JWT correctly when alg is changed to HS256 from RS256. HS256 is a symmetric encryption method, the server side is using the same key to generate and validate the JWT. Whereas, RS256 is an asymmetric encryption method, the JWT payload was signed with its private key and validated with the public key, which is known to the public. Now An attacker creates the token by setting the signing algorithm to a symmetric HS256 instead of an asymmetric RS256, leading the API to blindly verify the token using the HS256 algorithm using the public key as a secret key. Since the RSA public key is known, the attacker can correctly forge valid JWTs and bypass the validation method.

Lack of kid header parameter validation

Thekid(key ID) Header Parameter is a hint indicating which key was used to secure the JWS. This parameter allows originators to explicitly signal a change of key to recipients. With the key identifier, the consumer of a JWT can retrieve the proper cryptographic key to verify the signature. This simple mechanism works well when both the issuer and consumer have access to the same cryptographic key store.

Since the attacker can modify the kid header parameter, attacker can supply any values in there when it is sent to the sever. If the server is not validating or sanitizing the kid value correctly, it could lead to severe damage.

For example, the kid value in the JWT header is specifying the location of the JWT secret to sign the JWT payload

{ "alg": "HS256", "typ": "JWT", "kid": "http://localhost:3000/vault/privKey.key"}

For example, the kid value in the JWT header is specifying the location of the JWT secret to sign the JWT payload

{ "alg": "HS256", "typ": "JWT", "kid": "http://evil.com/privKey.key" //Private key supplied by the attacker}

Now, if the attacker is providing his own private key to the kid parameter and adjust the JWT token, he would be able to generate any valid JWT token.

Other wrong implementation

The above implementation mistakes could lead to very severe security issues, for example, account hijacking and authentication bypass. There are some other implementation bad practice should be avoid when using JWT token.

  • Use JWT token as session cookie. Some applications are using JWT token as a session cookie and it could cause havoc. Let’s say you have a token and you revoke it due to a user logout or any other action, you could not really invalidate the token before its expiration has been reached unless you keep a DB to store these tokens and build a revocation list, which is not the intention of using a stateless JWT.
  • Leak the JWT in referrer header. It is common that a developer attaches the JWT in a URL, for example, user registering and password reset service, and the HTML page of the URL are loading some 3rd party web pages. As a consequence, the JWT could be leaked to 3rd party web pages via referer header if noreferrer is not probably deployed in the web application.

Conclusion

JWT are adopted by more and more applications over the web.Ifused correctly, it could help you to build a robust and agile authentication, authorization and information key functions.However, ifmisused or implemented incorrectly, this technology may put entire systems atrisk. ThisJWT Security Cheat Sheetprovides an overview of all these best practices when using JWT in your applications.

Using JWT? You need avoid these implementation mistakes (2024)

FAQs

Why shouldn't you use JWT? ›

The reason to avoid JWTs comes down to a couple different points:
  • The JWT specification is specifically designed only for very short-live tokens (~5 minute or less). ...
  • JWTs which just store a simple session token are inefficient and less flexible than a regular session cookie, and don't gain you any advantage.

How to handle JWT error? ›

Check to make sure the verifier field is set correctly. The JWT is not signed with the correct key(JWK). The JWKS endpoint is not reachable or doesn't return a valid JWK that was used to sign the JWT. The JWKS endpoint is incorrect on the Web3Auth Dashboard.

What is the problem with JWT? ›

JWT attacks involve a user sending modified JWTs to the server in order to achieve a malicious goal. Typically, this goal is to bypass authentication and access controls by impersonating another user who has already been authenticated.

What are the risks of JWT authentication? ›

JWTs should be lightweight, and more importantly, they shouldn't carry sensitive data. Risks: Data Exposure: Overloading tokens can expose unnecessary user data if intercepted. Performance: Larger payloads might impact network performance, especially in systems that transmit JWTs frequently.

Should you use JWT for authentication? ›

A very common use for JWT — and perhaps the only good one — is as an API authentication mechanism. JWT technology is so popular and widely used that Google uses it to let you authenticate to its APIs. On the client side, you create the token (there are many libraries for this) using the secret token to sign it.

How to safely use JWT? ›

Secure JWT storage: Avoid storing JWTs in local storage or cookies, and opt for more secure alternatives like HTTP-only cookies or server-side session management. Validate and verify JWTs: Always validate JWTs upon receipt and verify the signature to ensure they haven't been tampered with.

What is replacing JWT? ›

If we look back at the JWT criticisms around algorithm selection, PASETO's versioning only removes the use of the none algorithm. PASETO is designed as a replacement for JWTs, particularly their use in protocols such as OAuth and OpenID Connect.

What the heck is JWT? ›

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.

Why is JWT better than API key? ›

The credentials can either be a cryptographically secure JSON Web Token (JWT) signed with the client's private key or a secret value generated from your authorization server. A private key JWT is more secure, as you won't risk exposing the secret value that accidentally creates similar access concerns as an API key.

What are the weaknesses of JWT? ›

Disadvantages of JWT Authentication:

Limited Token Expiry Control: Once issued, JWTs remain valid until they expire. Revoking a JWT before expiration requires additional complexity, such as token blacklisting. Security Risks: If the secret key used to sign JWTs is compromised, attackers can create forged tokens.

Can someone steal my JWT token? ›

Because JWTs are used to identify the client, if one is stolen or compromised, the attacker has full access to the user's account in the same way they would if the attacker had compromised the user's username and password instead.

Are JWT tokens unsafe? ›

It's important to remember that JWT safety depends greatly on how tokens are used and validated. Just because a JWT contains a cryptographic signature it doesn't automatically mean that it's safe, or that you should blindly trust the token.

Are JWT tokens insecure? ›

Some web applications rely on JSON Web Tokens (JWTs) for stateless authentication and access control instead of stateful ones with traditional session cookies. Some implementations are insecure and allow attackers to bypass controls, impersonate users, or retrieve secrets.

Is JWT deprecated? ›

One of those credential types, Service Account (JWT) credentials, has been deprecated in favor of the OAuth Server-to-Server credentials. New Service Account (JWT) credentials cannot be created on or after June 3, 2024, and existing JWT credentials will not work on or after Jan 27, 2025.

Top Articles
Latest Posts
Article information

Author: Reed Wilderman

Last Updated:

Views: 6222

Rating: 4.1 / 5 (72 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Reed Wilderman

Birthday: 1992-06-14

Address: 998 Estell Village, Lake Oscarberg, SD 48713-6877

Phone: +21813267449721

Job: Technology Engineer

Hobby: Swimming, Do it yourself, Beekeeping, Lapidary, Cosplaying, Hiking, Graffiti

Introduction: My name is Reed Wilderman, I am a faithful, bright, lucky, adventurous, lively, rich, vast person who loves writing and wants to share my knowledge and understanding with you.