TNS
VOXPOP
Favorite Social Media Timesink
When you take a break from work, where are you going?
Instagram/Facebook
0%
Discord/Slack
0%
LinkedIn
0%
Video clips on TikTok/YouTube
0%
X, Bluesky, Mastodon et al...
0%
Web surfing
0%
I do not get distracted by petty amusements
0%
Networking / Security / Software Development

JWTs: Connecting the Dots: Why, When and How

Understanding the fundamentals of JSON web tokens is essential. When incorrectly configured or misused, they can give users access beyond their privileges.
Mar 20th, 2023 7:10am by
Featued image for: JWTs: Connecting the Dots: Why, When and How

JSON web tokens (JWTs) are great — they are easy to work with and stateless, requiring less communication with a centralized authentication server. JWTs are handy when you need to securely pass information between services. As such, they’re often used as ID tokens or access tokens.

This is generally considered a secure practice as the tokens are usually signed and encrypted. However, when incorrectly configured or misused, JWTs can lead to broken object-level authorization or broken function-level authorization vulnerabilities. These vulnerabilities can expose a state where users can access other data or endpoints beyond their privileges. Therefore, it’s vital to follow best practices for using JWTs.

Knowing and understanding the fundamentals of JWTs is essential when determining a behavior strategy.

What Are JWTs?

JWT is a standard defined in RFC 7519, and its primary purpose is to pass a JSON message between two parties in a compact, URL-safe and tamper-proof way. The token looks like a long string divided into sections and separated by dots. Its structure depends on whether the token is signed (JWS) or encrypted (JWE).

JWS Structure

JWE Structure

Are JWTs Secure? 

The short answer is that it depends. The security of JWTs is not a given. As mentioned above, JWTs are often considered secure because they are signed or encrypted, but their security really depends on how they are used. A JWT is a message format in which structure and security measures are defined by the RFC, but it is up to you to ensure their use does not harm the safety of your whole system in any way.

When to Use JWTs

Should they be used as access and ID tokens?

JWTs are commonly used as access tokens and ID tokens in OAuth and OpenID Connect flows. They can also serve different purposes, such as transmitting information, requesting objects in OpenID Connect, authenticating applications, authorizing operations and other generic use cases.

Some say that using JWTs as access tokens is an unwise decision. However, in my opinion, there is nothing wrong if developers choose this strategy based on well-done research with a clear understanding of what JWTs essentially are. The worst-case scenario, on the other hand, is to start using JWTs just because they are trendy. There is no such thing as too many details when it comes to security, so following the best practices and understanding the peculiarities of JWTs is essential.

JWTs are by-value tokens containing data intended for the API developers so that APIs can decode and validate the token. However, if JWTs are issued to be used as access tokens to your clients, there is a risk that client developers will also access this data. You should be aware that this may lead to accidental data leaks since some claims from the token should not be made public. There is also a risk of breaking third-party integrations that rely on the contents of your tokens.

Therefore, it is recommended to:

  • Remember that introducing changes into JWTs used as access tokens may cause problems with app integrations.
  • Consider switching to Phantom tokens or Split tokens when sensitive or personal information is used in a token. In these cases, an opaque token should be used outside your infrastructure.
  • When a high level of security is required, use Proof-of-Possession tokens instead of Bearer tokens by adding a confirmation claim to mitigate the risks of unwanted access.

Should they be used to handle sessions?

An example of improper use of JWTs is choosing them as a session-retention mechanism and replacing session cookies and centralized sessions with JWTs. One of the reasons you should avoid this tactic is that JWTs cannot be invalidated, meaning you won’t be able to revoke old or malicious sessions. Size issues pose another problem, as JWTs can take up a lot of space. Thus, storing them in cookies can quickly exceed size limits. Solving this problem might involve storing them elsewhere, like in local storage, but that will leave you vulnerable to cross-site scripting attacks.

JWTs were never intended to handle sessions, so I recommend avoiding this practice.

Claims Used in JWTs and How to Handle Them

JWTs use claims to deliver information. Properly using those claims is essential for security and functionality. Here are some basics on how to deal with them.

Claim Function Best Practices
iss Shows the issuer of the token
  • Always check against an allowlist to ensure it has been issued by someone you expect to issue it.
  • The value of the claim should exactly match the value you expect it to be.
sub Indicates the user or other subject of the token
  • As anyone can decode the token and access the data, avoid using sensitive data or PII.
aud Indicates the receiver of the token
  • Always verify that the token is issued to an audience you expect.
  • Reject any request intended for a different audience.
exp Indicates the expiration time for the token
  • Use a short expiration time — minutes or hours at maximum.
  • Remember that server times can differ slightly between different machines.
  • Consider allowing a clock skew when checking the time-based values.
  • Don’t use more than 30 seconds of clock skew.
  • Use iat to reject tokens that haven’t expired but which, for security reasons, you deem to be issued too far in the past.
nbf Identifies the time before which the JWT must not be accepted for processing
iat Identifies the time at which the JWT was issued
jti Provides a unique identifier for the token
  • It must be assigned in a way that prevents the same value from being used with a different object.

Validating Tokens

It is important to remember that incoming JWTs should always be validated. It doesn’t matter if you only work on an internal network (with the authorization server, the client and the resource server not connected through the internet). Environment settings can be changed, and if services become public, your system can quickly become vulnerable. Implementing token validation can also protect your system if a malicious actor is working from the inside.

When validating JWTs, always make sure they are used as intended:

  • Check the scope of the token.
  • Don’t trust all the claims. Verify whether keys contained in claims, or any URIs, correspond to the token’s issuer and contain a value that you expect.

Best Algorithms to Use with JWTs

The registry for JSON Web Signatures and Encryption Algorithms lists all available algorithms that can be used to sign or encrypt JWTs. It is also very useful to help you choose which algorithms should be implemented by clients and servers.

Currently, the most recommended algorithms for signing are EdDSA or ES256. They are preferred over the most popular one, RS256, as they are much faster than the well-tried RS256.

No matter the token type — JWS or JWE — they contain an alg claim in the header. This claim indicates which algorithm has been used for signing or encryption. This claim should always be checked with a safelist of algorithms accepted by your system. Allowlisting helps to mitigate attacks that attempt to tamper with tokens (these attacks may try to force the system to use different, less secure algorithms to verify the signature or decrypt the token). It is also more efficient than denylisting, as it prevents issues with case sensitivity.

How to Sign JWTs

One thing to remember about JWS signatures is that they are used to sign both the payload and the token header. Therefore, if you make changes to either the header or the payload, whether merely adding or removing spaces or line breaks, your signature will no longer validate.

My recommendations when signing JWTs are the following:

  • To avoid duplicating tokens, add a random token ID in the jti claim. Many authorization servers provide this opportunity.
  • Validate signatures, keys and certificates. Keys and certificates can be obtained from the authorization server. A good practice is to use an endpoint and download them dynamically. This makes it easy to rotate keys in a way that would not break the implementation.
  • Check the keys and certificates sent in the header of the JWS against an allowlist, or validate the trust chain for certificates.

Symmetric keys are not recommended for use in signing JWTs. Using symmetric signing presupposes that all parties need to know the shared secret. As the number of involved parties grows, it becomes more difficult to guard the safety of the secret and replace it if it is compromised.

Another problem with symmetric signing is that you don’t know who actually signed the token. When using asymmetric keys, you’re sure that the JWT was signed by whoever possesses the private key. In the case of symmetric signing, any party with access to the secret can also issue signed tokens. Always choose asymmetric signing. This way, you’ll know who actually signed the JWT and make security management easier.

JWTs and API Security

API security has become one of the main focuses of cybersecurity efforts. Unfortunately, vulnerabilities have increased as APIs have become critical for overall functionality. One of the ways to mitigate the risks is to ensure that JWTs are used correctly. JWTs should be populated with scopes and claims that correspond well to the client, user, authentication method used and other factors.

Conclusion

JWTs are a great technology that can save developers time and effort and ensure the security of APIs and systems. To fully reap their benefits, however, you must ensure that choosing JWTs fits your particular needs and use case. Moreover, it is essential to make sure they are used correctly. To do this, follow the best practices from security experts.

Here are some additional guidelines:

Group Created with Sketch.
TNS owner Insight Partners is an investor in: Pragma.
THE NEW STACK UPDATE A newsletter digest of the week’s most important stories & analyses.