JWT Token Security Best Practices | Curity (2024)

On this page

JSON Web Tokens Introduction

JSON Web Tokens (JWTs) are quite common in the OAuth and OpenID Connect world. We're so used to them that we oftendon't pay much attention to how they're actually used. The general opinion is that they're good for being used as IDtokens or access tokens and that they're secure — as the tokens are usually signed or even encrypted. You have to rememberthough, that JWT is not a protocol but merely a message format. The RFC just shows you how you can structure a given messageand how you can add layers of security, that will protect the integrity and, optionally, the content of the message. JWTsare not secure just because they are JWTs, it's the way in which they’re used that determines whether they are secure or not.

This article shows some best practices for using JWTs so that you can maintain a high levelof security in your applications. These practices are what we recommend at Curity and are based on community standards writtendown in RFCs as well as our own experience from working with JWTs.

What is a JWT Token?

A JSON Web Token (JWT, pronounced "jot") is a compact and URL-safe way ofpassing a JSON message between two parties. It's a standard, defined in RFC 7519.The token is a long string, divided into parts separated by dots. Each part is base64 URL-encoded.

What parts the token has depends on the type of the JWT: whether it's a JWS (a signed token) or a JWE (an encrypted token). If the tokenis signed it will have three sections: the header, the payload, and the signature. If the token is encrypted it will consistof five parts: the header, the encrypted key, the initialization vector, the ciphertext (payload), and the authentication tag.Probably the most common use case for JWTs is to utilize them as access tokens and ID tokens in OAuth and OpenID Connect flows,but they can serve different purposes as well.

1. JWTs Used as Access Tokens

JWTs are by-value tokens. This means that they contain data. Even if you can't read that data with your own eyes, it's stillthere and is quite easily available. Whether it's a problem or not depends on the intended audience of the token. AnID token is intended for the client's developers. You expect it to be decoded and its data used by the client. An accesstoken, on the other hand, is intended for API developers. The API should decode and validate the token. If youissue JWT access tokens to your clients you have to remember that client developers will be able to accessthe data inside that token. And believe us — if they can, they will. This should make you consider a few things:

  • Some developers can start using the data from the JWT in their applications. This isn't a problem in itself but can explodethe minute you decide to introduce some changes to the structure of the data in your JWT. Suddenly many integrating appscan stop working as they won't be prepared for the new structure (e.g., some fields missing, or a change to the max length ofa field).
  • As everyone can read what is inside the token, privacy should be taken into account. If you want to put sensitivedata about a user in a token, or even Personally Identifiable Information (PII), remember that anyone can decode the tokenand access the data. If such information can't be removed from the token you should consider switching tothe Phantom Token approach orthe Split Token approach, where an opaquetoken is used outside your infrastructure, and JWTs are only available to your APIs, thanks to integration with anAPI gateway.
  • Users’ private data is not the only information that can be leaked in a JWT. You should make sure that you don't putany valuable information about your API in the token. Anything that would help attackers to breach your API.

It's also good to keep in mind, that access tokens are most often used as bearer tokens. That means that you accept thetoken from whoever presented it to you — it's pretty much like paying with cash in a shop. If you find a $10 bill lyingin the street, and pay with it for a coffee, it will be accepted, as long as it's a genuine banknote. The same appliesto bearer access tokens. If that could pose problems to your application, you can change the bearer token into a Proof ofPossession token (a PoP token) by adding a cnf claim — a confirmation claim. The claim contains information that allows the resource server to verify whether the holder is allowed to use the given token, e.g., a fingerprintof the client’s certificate.

2. Avoid JWTs With Sensitive Data on the Front Channel

When it comes to access tokens, they can easily be replaced by opaque tokens (as mentioned in the previous section), but the ID token is always a JWT. This means that you should put extra care into what is available in the JWT so that no sensitive data is unintentionally revealed. It will be much safer for your UI client to call the user info endpoint and get the user's data from there instead of keeping it directly in the ID token.

Once tokens are cleared of sensitive data there will be no incentive for encrypting them. Even though encryption might sound like an excellent solution to keeping data private, the reality is that it is hard to configure and maintain secure encryption mechanisms. What is more, encryption requires much more computational resources to be used, something that might become a burden for high-traffic applications.

3. What Algorithms to use

Regardless if the token is signed (a JWS) or encrypted (a JWE) it will contain an alg claim in the header. It indicateswhich algorithm has been used for signing or encryption. When verifying or decrypting the token you should always check thevalue of this claim with a whitelist of algorithms that your system accepts. This mitigates an attack vector where someonewould tamper with the token and make you use a different, probably less secure algorithm to verify the signature or decryptthe token. Whitelisting algorithms is preferred over blacklisting, as it prevents any issues with case sensitivity. Therewere attacks on APIs that leveraged the fact that the algorithm noNe was interpreted as none (so no validation was performed) but was not discarded by theresource server (even though none was forbidden).

The special case of the none value in the alg claim tells clients and resource servers that the JWS is actually not signed at all. This option isnot recommended, and you should be absolutely sure what you're doing if you want to enable unsigned JWTs. This would usuallymean that you have strong certainty of the identity of both the issuer of the token and the client that handles the token,and you're absolutely sure that no party could have tampered with the token in transit.

The registry for JSON Web Signatures and Encryption Algorithms lists all available algorithms that can be used to sign or encrypt JWTs.It also tells you which algorithms are recommended to be implemented by clients and servers, given the current state ofknowledge on cryptography security. If you want to ensure financial-grade security to your signature then have a look at the recommendations outlined in the Financial-grade API security profile.

When signing is considered, elliptic curve-based algorithms are considered more secure.The option with the best security and performance is EdDSA, though ES256 (The Elliptic Curve Digital Signature Algorithm (ECDSA) using P-256 and SHA-256) is also a good choice.The most widely used option, supported by most technology stacks, is RS256 (RSASSA-PKCS1-v1_5 using SHA-256).The former ones are a lot faster than the latter, which is one of the main reasons for the stronger recommendation. The latterhas been around much longer and offers better support in different languages and implementations. Still, if your setupenables this, and you're pretty sure that your clients will be able to use it, you should go for the EdDSA or ES256.

If you really need to use symmetric keys, then HS256 (HMAC using SHA-256) should be your choice — though using symmetrickeys is not recommended, take a look at When to Use Symmetric Signing to learn why.

4. When to Validate the Token

The rule of thumb is — you should always validate an incoming JWT. You should do it, even if you're working on an internalnetwork — where the authorization server, the client, and the resource server aren't connected through the Internet. Youshouldn't rely on your environment settings to be part of your security scheme. If you move your services to a public domain,the threat model will change, and you will have to remember to update your security measures — experience shows that thisis very often overlooked. Moreover, implementing token validation from the start will guard you against situations where someonemanages to break into your network, or you would have a malicious actor in your organization.

The one case when you could consider omitting to check the signature of the token is when you first get it in the responsefrom the token endpoint of the authorization server using TLS. You should definitely validate a token if using the implicit flow,and the token is sent back to the client by means of a redirect URI, as in such a case there is a greater risk of someonetampering with the token before you manage to retrieve it.

5. Always Check the Issuer

Another claim that you should always check against a whitelist is the iss claim. When using the JWT you should besure that it has been issued by someone you expected to issue it. This is especially important if you adhere to anothergood practice and dynamically download the keys needed to validate or decrypt tokens. If someone should send you aforged JWT, with their issuer in it, and you then download keys from that issuer, then your application would validatethe JWTs and accept them as genuine.

This good practice can also be explained in other words: if the token contains the iss claim you should always confirmthat any cryptographic keys used to sign or encrypt the token actually belong to the issuer. How to verify this will bedifferent for different implementations. E.g., if you're using OpenID Connect the issuer must be a URL using the HTTPS scheme.This makes it easy to confirm the ownership of the keys or certificates. Thus, it's good practice to alwaysuse such URLs as the issuer value. If this is not the case, you should make sure to get to know how to check this ownership.

Also, remember that the value of the iss claim should match exactly the value that you expect it to be. If youexpect the issuer to be https://example.com, this is not the same as https://example.com/secure!

6. Always Check the Audience

The resource server should always check the aud claim and verify that the token was issued to an audience that the server is part of (as the aud claim can contain an array, the resource server should check if the correct value is present in that array). Any request thatcontains a token intended for different audiences should be rejected. This helps to mitigate attack vectors where one resource server wouldobtain a genuine access token intended for it, and then use it to gain access to resources on a different resource server,which would not normally be available to the original server.

An ID token must contain the client ID in the aud claim (though it can also contain other audiences). You expect the tokento be decoded by the client, so it can use the data inside it. This token should not be passed to anyone else. Clients should discard ID tokens that do not contain their ID in the audience claim — these tokens are not meant for this client and should not be used by it.

For access tokens, it is a good practice to use the URL of the API that the tokens are intended for.

7. Make Sure Tokens are Used as Intended

JWTs can be used as access tokens or ID tokens, or sometimes for other purposes. It is thus important todifferentiate the types of tokens. When validating JWTs, always make sure that they are used as intended.E.g., a resource server should not accept an ID token JWT as an access token. This can be achieved in different ways and will depend onyour concrete use case and implementation. Here are some examples:

  • You can check the scope of the token. ID tokens don't have scopes, so checking whether an access token has any or aconcrete scope will help you differentiate them.
  • As noted before, tokens should have different values of the aud claim. If this is the case, you can use that claim's value to check the token type.
  • The Curity Identity Server sets a purpose claim on the token, with values of either access_token or id_token.
  • Some authorization servers might set the not-yet-standardized typ claim in the token header to at+JWT for access tokens. If your server supports that, it can be used to differentiate tokens.
  • Different types of tokens could use different keys for signing. Your services will then reject access tokens signed with keys used for issuing ID tokens.
  • You can use sets of required claims for different types of tokens. Your services can validate whether the received token contains specific claims that you expect from an access token.

8. Don't Trust All the Claims

Claims in a JWT represent pieces of information asserted by the authorization server. The token is usually signed, so its recipient can verify the signature and thus trust the values of the payload's claims. You should be wary, however, when dealing with some claims in the token's header. The JWT's header can contain claims that are used in the process of signature verification. For example:the kid claim can contain the ID of the key that should be used for verification,the jku can contain a URI pointing to the JSON Web Key Set — a set that contains the verification key,the x5c can claim contain the public key certificate corresponding to the signature key, etc.You should make extra care when using these values straight from the token. If these claims are spoofed they can point your service to forged verification keys that will trick your service into accepting malicious access tokens. As noted before, make sure to verify whether keys contained in such claims, or any URIs, correspond to the token's issuer, or that they contain a value that you expect.

9. Dealing With Time-Based Claims

JWTs are self-contained, by-value tokens and it is very hard to revoke them, once issued and delivered to the recipient.Because of that, you should use as short an expiration time for your tokens as possible — minutes or hours at maximum. Youshould avoid giving your tokens expiration times in days or months.

Remember that the exp claim, containing the expiration time, is not the only time-based claim that can be used for verification.The nbf claim contains a "not-before" time. The token should be rejected if the current time is before the time in thenbf claim. Another time-based claim is iat — issued at. You can use this claim to reject tokens that you deem too old tobe used with your resource server.

When working with time-based claims remember that server times can differ slightly between different machines. You shouldconsider allowing a clock skew when checking the time-based values. This should be values of a few seconds, and we don'trecommend using more than 30 seconds for this purpose, as this would rather indicate problems with the server, nota common clock skew.

10. How to Work With the Signature

In the case of a signed JWT — a JWS — you have to remember that the signature is used to sign not only the payload of the tokenbut also the header. Any change in the header or the payload would generate a different signature. This doesn't evenhave to be a change in the values of claims — adding or removing spaces or line breaks will also create a differenttoken signature.

It's worth noting that in order to mitigate a situation where two tokens would be created with exactly the same signature(so two tokens created in the same second, for the same client and user, with the same scope, etc.) many authorizationservers add a random token ID in the jti claim. Thanks to this you can be sure that two different tokens willnever have the same signature.

Signatures require keys or certificates to be properly validated. These keys or certificates can be obtained from theauthorization server in a few different ways. You can get the keys from the authorization server in an onboarding process, and makesure that all of your resource servers have access to those keys. This however creates a problem when the keys or certificateschange. That's why it's good practice to always use an endpoint and dynamically download the keys or certificates fromthe authorization server (caching responses accordingly to what the server returns in the cache control headers). Thisallows for an easy key rotation, and any such rotation will not break your implementation.

Remember that if the keys or certificates are sent in the header of the JWT, you should always check whether they belong to the expected issuer, for example, validate the trust chain in certificates.

As noted before, the alg claim in the header must be checked against an allow list.

11. When to use Symmetric Signing

The rule of thumb here is to try to avoid using symmetric signing at all. Nowadays, there are probably not many use cases whereyou would have to use symmetric signing instead of asymmetric. When using symmetric keys then all the parties needto know the shared secret. When the number of involved parties grows it becomes more and more difficult to guard the safetyof the secret, and to replace it, in case it is compromised.

Another problem with symmetric signing is the proof of who actually signed the token. When using asymmetric keys you're surethat the JWT was signed by whoever is in possession of the private key. In the case of symmetric signing, any party that hasaccess to the secret can also issue signed tokens.

If, for some reason, you have to use symmetric signing try to use ephemeral secrets, which will help increase security.

12. Pairwise Pseudonymous Identifiers

The OpenID Connect standard introduces Pairwise Pseudonymous Identifiers (PPID) that can be used instead of a plain user ID. A PPIDis an obfuscated user ID, unique for a given client. This helps to improve users' privacy. Especially if the user ID is represented by sensitivedata e.g., en e-mail or the Social Security Number. Thanks to PPID, the client can still differentiateusers, but will not get any excess information. Have a look at the Pairwise Pseudonymous Identifiers articleto learn more.

13. Do not use JWTs for Sessions

There is a popular belief among web developers that JWTs have some benefits for use as a session retention mechanism —instead of session cookies and centralized sessions. This should not be considered good practice. JWTs were neverconsidered for use with sessions, and using them in such a way may actually lower the security of your applications. Ifyou're interested to know what the exact reasons against such use of JWTs are, have a look at these articles:

Conclusion

This article has explored the best practices when using JSON Web Tokens as a way of strengthening API Security in web applications.It's important to remember that JWT safety depends greatly on how tokens are used and validated. Just because a JWTcontains a cryptographic signature it doesn't automatically mean that it's safe, or that you should blindly trust the token.Unless good practices are observed your APIs can become vulnerable to cyber-attacks.

The good practices outlined in this article are true at the time of writing and we are making sure to keep them up to date. You should remember, however, that security standardsand the security levels of cryptography can change quite rapidly and it's good to keep an eye on what is happeningin the industry. You can follow any changes in RFCs that talk about the good practices for JWTs:in RFC 8725 JSON Web Token Best Current Practicesand in RFC 7518 JSON Web Algorithms (JWA).

Join our Newsletter

Get the latest on identity management, API Security and authentication straight to your inbox.

Start Free Trial

Try the Curity Identity Server for Free. Get up and running in 10 minutes.

Start Free Trial

  1. Home
  2. Resources
  3. API Security
  4. JWT Security Best Practices

Was this helpful?

JWT Token Security Best Practices | Curity (2024)

FAQs

JWT Token Security Best Practices | Curity? ›

Here are some best practices for implementing JWTs: Use strong algorithms like HMAC-SHA256 or RSA to sign and encrypt your tokens. Avoid using weak algorithms like HMAC-MD5. Set an expiration time for the JWT to limit its validity period.

How to secure your JWT token? ›

Here are some best practices for implementing JWTs: Use strong algorithms like HMAC-SHA256 or RSA to sign and encrypt your tokens. Avoid using weak algorithms like HMAC-MD5. Set an expiration time for the JWT to limit its validity period.

What are the best practices to store JWT? ›

To keep them secure, you should always store JWTs inside an HttpOnly cookie. This is a special kind of cookie that's only sent in HTTP requests to the server. It's never accessible (both for reading and writing) from JavaScript running in the browser.

What is the security flaw in 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 provide security to JWT token content? ›

Security of JWTs

The information contained within the JSON object can be verified and trusted because it is digitally signed. Although JWTs can also be encrypted to provide secrecy between parties, Auth0-issued JWTs are JSON Web Signatures (JWS), meaning they are signed rather than encrypted.

How can JWT be prevented from being stolen? ›

Preventive steps by aircraft owners should include the following: (1) store the aircraft in a locked hanger or park it in a well-lighted and secure area; (2) use metal aircraft tiedown straps of sufficient strength to discourage cutting; (3) install antitheft devices, such as wheel locks; (4) complete a list of all ...

How do I securely store JWT tokens in my browser? ›

Optimal Secure Solution: Save JWT Tokens in the browser's memory and store the refresh token in a cookie
  1. Step 1: Generate and issue tokens. ...
  2. Step 2: Save the JSON web token in the browser session. ...
  3. Step 3: Save the refresh token in a secure HttpOnly Cookie. ...
  4. Step 4: How to refresh the JSON web tokens.
May 9, 2023

Which security algorithm is best for JWT? ›

The option with the best security and performance is EdDSA, though ES256 (The Elliptic Curve Digital Signature Algorithm (ECDSA) using P-256 and SHA-256) is also a good choice.

Why JWTs are bad for authentication? ›

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. The JWT specification itself is not trusted by security experts. This should preclude all usage of them for anything related to security and authentication.

What is better than JWT security? ›

Security: OAuth is a secure way to manage authorization flows, while JWT is a lightweight and self-contained token. It does not provide security on its own, but can be secure as part of a well designed authentication system.

How to encrypt a JWT token? ›

Encrypting a JWT for a given recipient requires their public RSA key. The decryption takes place with the corresponding private RSA key, which the recipient must keep secret at all times. To create an RSA encrypter with Nimbus JOSE+JWT for a given public key: JWEEncrypter encrypter = new RSAEncrypter(rsaPublicKey);

What is the JWT secret key? ›

Secure: JWTs are digitally signed using either a secret (HMAC) or a public/private key pair (RSA or ECDSA) which safeguards them from being modified by the client or an attacker. Stored only on the client: You generate JWTs on the server and send them to the client. The client then submits the JWT with every request.

What if a JWT token is stolen? ›

One of the most important steps is to ask your clients to change their passwords immediately if there's an instance where the JWT token is stolen. Changing the password of an account will prevent attackers from exploiting the account and would eventually help in avoiding a data breach.

How do I secure my authentication token? ›

JSON Web Token Best Practices
  1. Keep it secret. Keep it safe. ...
  2. Do not add sensitive data to the payload. Tokens are signed to protect against manipulation and are easily decoded. ...
  3. Give tokens an expiration. ...
  4. Embrace HTTPS. ...
  5. Consider all of your authorization use cases.

How do I authorize my JWT token? ›

To authenticate a user, a client application must send a JSON Web Token (JWT) in the authorization header of the HTTP request to your backend API. API Gateway validates the token on behalf of your API, so you don't have to add any code in your API to process the authentication.

What is the best way to secure JWT token in react? ›

However, storing JWT tokens in local storage or session storage can be risky since they can be stolen by attackers using Cross-Site Scripting (XSS) attacks. Therefore, it's best to store the token in an HTTP-only cookie instead of local storage or session storage.

Top Articles
Top Cisco Courses in 2024- Best Guide to Build Career in IT
7 surprising ways the public library can help you save money : Life Kit
Fighter Torso Ornament Kit
This website is unavailable in your location. – WSB-TV Channel 2 - Atlanta
Is Paige Vanzant Related To Ronnie Van Zant
Dairy Queen Lobby Hours
Insidious 5 Showtimes Near Cinemark Tinseltown 290 And Xd
P2P4U Net Soccer
Bluegabe Girlfriend
Chuckwagon racing 101: why it's OK to ask what a wheeler is | CBC News
Www.paystubportal.com/7-11 Login
Alaska Bücher in der richtigen Reihenfolge
Blue Ridge Now Mugshots Hendersonville Nc
Athens Bucket List: 20 Best Things to Do in Athens, Greece
Rosemary Beach, Panama City Beach, FL Real Estate & Homes for Sale | realtor.com®
Local Dog Boarding Kennels Near Me
Hair Love Salon Bradley Beach
Procore Championship 2024 - PGA TOUR Golf Leaderboard | ESPN
Wisconsin Women's Volleyball Team Leaked Pictures
Jinx Chapter 24: Release Date, Spoilers & Where To Read - OtakuKart
Craighead County Sheriff's Department
Obsidian Guard's Cutlass
Walmart Car Department Phone Number
Busted Campbell County
Mtr-18W120S150-Ul
Craigslistodessa
Southland Goldendoodles
Naya Padkar Gujarati News Paper
Account Now Login In
The Powers Below Drop Rate
His Only Son Showtimes Near Marquee Cinemas - Wakefield 12
Craigslist Maryland Baltimore
Chilangos Hillsborough Nj
Pawn Shop Open Now
Cpmc Mission Bernal Campus & Orthopedic Institute Photos
Directions To The Closest Auto Parts Store
Craigslist Farm And Garden Reading Pa
Exploring the Digital Marketplace: A Guide to Craigslist Miami
Here's Everything You Need to Know About Baby Ariel
Cabarrus County School Calendar 2024
My Eschedule Greatpeople Me
Tom Kha Gai Soup Near Me
Caphras Calculator
CrossFit 101
Theater X Orange Heights Florida
Headlining Hip Hopper Crossword Clue
552 Bus Schedule To Atlantic City
Rheumatoid Arthritis Statpearls
Www Ventusky
Sj Craigs
David Turner Evangelist Net Worth
Denys Davydov - Wikitia
Latest Posts
Article information

Author: Francesca Jacobs Ret

Last Updated:

Views: 5457

Rating: 4.8 / 5 (48 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Francesca Jacobs Ret

Birthday: 1996-12-09

Address: Apt. 141 1406 Mitch Summit, New Teganshire, UT 82655-0699

Phone: +2296092334654

Job: Technology Architect

Hobby: Snowboarding, Scouting, Foreign language learning, Dowsing, Baton twirling, Sculpting, Cabaret

Introduction: My name is Francesca Jacobs Ret, I am a innocent, super, beautiful, charming, lucky, gentle, clever person who loves writing and wants to share my knowledge and understanding with you.