JWT authentication: Best practices and when to use it - LogRocket Blog (2024)

Editor’s note: This JWT authentication tutorial was last updated on 1 July 2021. It may still contain information that is out of date.

In this JWT authentication tutorial, you’ll learn when to use JWT, why you shouldn’t use JWT for sessions, and how to store JWTs in cookies to prevent security issues. We’ll also go over some general JWT best practices.

Here’s what we’ll cover:

  • What is JWT?
  • When to use JWT authentication
  • Why you shouldn’t use JWTs as session tokens
  • Using JWT for API authentication
  • How to expire a single JWT token
  • How to securely store JWTs in a cookie
  • Using JWT for SPA authentication
  • Using JWT to authorize operations across servers
  • How to choose the best JWT library

JSON Web Tokens (JWT) is a JSON-encoded representation of a claim or claims that can be transferred between two parties.

Though it’s a very popular technology, JWT authentication comes with its share of controversy. Some say you should never use it. Others sayJWT authentication is amazing.

The truth lies somewhere in between: the value of using JWT depends on your use case and project requirements.

Before we dig any deeper, let’s briefly review what JWT authentication is.

What is JWT?

A JWT is a mechanism to verify the owner of some JSON data. It’s an encoded, URL-safe string that can contain an unlimited amount of data (unlike a cookie) and is cryptographically signed.

When a server receives a JWT, it can guarantee the data it contains can be trusted because it’s signed by the source. No middleman can modify a JWT once it’s sent.

It’s important to note that a JWT guarantees data ownership but not encryption. The JSON data you store into a JWT can be seen by anyone that intercepts the token because it’s just serialized, not encrypted.

For this reason, it’s highly recommended to use HTTPS with JWTs (and HTTPS in general, by the way).

We’re not going to cover how JWTs are generated in detail. For an in-depth, up-to-date look at how JWT authentication works, check out “JWT authentication from scratch with Vue.js and Node.js.”

When to use JWT authentication

JWT is a particularly useful technology for API authentication and server-to-server authorization.

For a comprehensive guide on using JWT technology to authenticate APIs, check out “How to secure a REST API using JWT.

Why you shouldn’t use JWTs as session tokens

On the other hand, you should not use JWTs as session tokens by default. For one thing, JWT has a wide range of features and a large scope, which increases the potential for mistakes, either by library authors or users.

Another issue is that you can’t remove a JWT at the end of a session because it’s self-contained and there’s no central authority to invalidate them.

Finally, to put it simply, JWTs are relatively large. When used with cookies, this adds up to a ton of overhead per request.

Over 200k developers use LogRocket to create better digital experiencesLearn more →

Using JWTs for session tokens might seem like a good idea at first because:

  • You can store any kind of user details on the client
  • The server can trust the client because the JWT is signed, and there is no need to call the database to retrieve the information you already stored in the JWT
  • You don’t need to coordinate sessions in a centralized database when you get to the eventual problem of horizontal scaling

Ultimately, if you already have a database for your application, just use a sessions table and use regular sessions as provided by the server-side framework of choice.

Why? There is a cost involved in using JWTs: they are sent for every request to the server and it’s always a high cost compared to server-side sessions.

Also, while the security risks are minimized sending JWTs using HTTPS, there is always the possibility that it’s intercepted and the data deciphered, exposing your user’s data.

Using JWT for API 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.

The idea is simple: you get a secret token from the service when you set up the API:

JWT authentication: Best practices and when to use it - LogRocket Blog (3)

On the client side, you create the token (there are many libraries for this) using the secret token to sign it.

When you pass it as part of the API request, the server will know it’s that specific client because the request is signed with its unique identifier:

JWT authentication: Best practices and when to use it - LogRocket Blog (4)

How to expire a single JWT token

How do you invalidate a single token? A no-effort solution is to change the server secret key, which invalidates all tokens. However, this is not ideal for users, who may have their tokens expired for no reason.

One way to do it is to add a property to your user object in the server database to reference the date and time at which the token was created.

A token automatically stores this value in theiat property. Every time you check the token, you can compare itsiat value with the server-side user property.

To invalidate the token, just update the server-side value. If iatis older than this, you can reject the token.

Another way to achieve this is by establishing a blocklist in your database cached in memory (or, even better, an allowlist).

How to securely store JWTs in a cookie

A JWT needs to be stored in a safe place inside the user’s browser. If you store it inside localStorage, it’s accessible by any script inside your page. This is as bad as it sounds; an XSS attack could give an external attacker access to the token.

To reiterate, whatever you do, don’t store a JWT in local storage (or session storage). If any of the third-party scripts you include in your page is compromised, it can access all your users’ tokens.

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 or writing) from JavaScript running in the browser.

Using JWT for SPA authentication

JWTs can be used as an authentication mechanism that does not require a database. The server can avoid using a database because the data store in the JWT sent to the client issafe.

Using JWT to authorize operations across servers

Say you have one server where you are logged in, SERVER1, which redirects you to another server SERVER2 to perform some kind of operation.

SERVER1 can issue you a JWT that authorizes you to SERVER2. Those two servers don’t need to share a session or anything to authenticate you. The token is perfect for this use case.

How to choose the best JWT library

How do you decide which JWT library to use in your project? A good place to start is this list of JWT libraries for token signing and verification.

The site contains a list of the most popular libraries that implement JWT, including libraries for Node.js, Python, Rust, Go, JavaScript, and many more.

Select your language of choice and pick the library that you prefer — ideally, the one with the highest number of green checks.

JWT authentication: Best practices and when to use it - LogRocket Blog (5)

Conclusion

JWT is a very popular standard you can use to trust requests by using signatures, and exchange information between parties. Make sure you know when it’s best used, when it’s best to use something else, and how to prevent the most basic security issues.

Cut through the noise of traditional error reporting with LogRocket

LogRocket is a digital experience analytics solution that shields you from the hundreds of false-positive errors alerts to just a few truly important items. LogRocket tells you the most impactful bugs and UX issues actually impacting users in your applications.

Then, use session replay with deep technical telemetry to see exactly what the user saw and what caused the problem, as if you were looking over their shoulder.

LogRocket automatically aggregates client side errors, JS exceptions, frontend performance metrics, and user interactions. Then LogRocket uses machine learning to tell you which problems are affecting the most users and provides the context you need to fix it.

Focus on the bugs that matter — try LogRocket today.

JWT authentication: Best practices and when to use it - LogRocket Blog (2024)

FAQs

When should JWT be used? ›

Information Exchange: JWTs are a good way of securely transmitting information between parties because they can be signed, which means you can be sure that the senders are who they say they are. Additionally, the structure of a JWT allows you to verify that the content hasn't been tampered with.

Why JWTs are bad for authentication? ›

The biggest problem with JWTs is that the token will continue to work until it expires, and the server has no easy way to revoke it. This could be extremely dangerous in situations such as the following: Logout doesn't actually log you out of the system.

What are the best practices for storing JWT? ›

JWT Security Best Practices
  • JWTs Used as Access Tokens.
  • Avoid JWTs With Sensitive Data on the Front Channel.
  • What Algorithms to use.
  • When to Validate the Token.
  • Always Check the Issuer.
  • Always Check the Audience.
  • Make Sure Tokens are Used as Intended.
  • Don't Trust All the Claims.

How often do you use JWT for authentication? ›

Authentication is done when a client successfully proves its identity via a login endpoint. If it's successful, the server will create JSON Web Token and send it in response to the client. The client will use this JWT on every request for a protected resource.

Why not to use JWT? ›

Problems with JWT

You can't. You (the server) can tell the user's client software to forget their JWT and hope they'll do it, but you can never be sure. Well, you could keep a list of tokens that are no longer valid - that is, the user has logged out and the token should be ignored.

What is better than JWT? ›

OAuth2, Passport, Spring Security, Auth0, and Keycloak are the most popular alternatives and competitors to JSON Web Token.

What are the common mistakes in JWT? ›

Most of the security issues discovered against JWT are caused by implementation mistakes.
  • Leak the secret key. ...
  • Using Predictable secret key. ...
  • Broken JWT Validation. ...
  • Lack of kid header parameter validation. ...
  • Other wrong implementation.
Sep 5, 2021

What is the security flaw in JWT? ›

The vulnerability is identified as CVE-2022-23529, rated high severity (CVSS 7.6). By exploiting this vulnerability, attackers could achieve remote code execution (RCE) on a server verifying a maliciously crafted JSON web token (JWT) request.

What is the safest form of authentication? ›

Multi-Factor Authentication (MFA)

The most common type of MFA is 2-Factor Authentication (2FA), which requires 2 separate types of credentials. 👍 Pros: Safer – 2 verifiers are better than 1. By using 2 or more separate authenticators, you can greatly limit the chances of anyone gaining access to your data.

What is safer than JWT? ›

PASETO is more secure than JWT and offers a simpler implementation. As a result, many developer communities started accepting it as a better alternative to JWT. Now that you too know the advantages of using PASETO over JWT, what are you going to use for your next project ?

What is the safest way to use JWT? ›

Use cookies to store JWT tokens – always secure, always httpOnly, and with the proper same site flag. This configuration will secure your client's data, it will prevent XSS and CSRF attack and also should simplify web application, because you do not have to care about using tokens manually on frontend code anymore.

What is the best expiry time for JWT? ›

The JWT access token is only valid for a finite period of time. Using an expired JWT will cause operations to fail. As you saw above, we are told how long a token is valid through expires_in . This value is normally 1200 seconds or 20 minutes.

What is the best algorithm for JWT? ›

JWTs signed with RSASSA-PKCS1-v1_5 have a deterministic signature, meaning that the same JWT header & payload will always generate the same signature. RSASSA-PKCS1-v1_5 has been around for a long time, but these days, you should generally prefer RSASSA-PSS (RSA with a probabilistic signature).

What if someone steals my JWT token? ›

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.

Is it good to store JWT in database? ›

A JWT needs to be stored in a safe place inside the user's browser. If you store it inside localStorage, it's accessible by any script inside your page. This is as bad as it sounds; an XSS attack could give an external attacker access to the token.

What are some pros and cons of JWT? ›

Short Version
👍 Pros👎 Cons
✅ Lesser DB Queries⭕ More payload with every API call
✅ Token contains all required info⭕ Trouble managing client from backend
✅ Easy to use⭕ Secret key compromise leads to system compromise
✅ Use across services⭕ Server cannot identify clients
1 more row
Aug 9, 2021

Is JWT obsolete? ›

JWT apps to be deprecated June 2023

The JWT app type will be completely deprecated as of June 2023. New and current users have 12 months to migrate their JWT based solutions to the Server-to-Server OAuth app type.

Why use JWT instead of cookie? ›

Tokens, usually referring to JSON Web Tokens (JWTs), are signed credentials encoded into a long string of characters created by the server. The main difference between cookies and tokens is their nature: tokens are stateless while cookies are stateful.

Which is more secure cookies or JWT? ›

You should never publicly share your JWT! (this JWT is no longer in use). Cookies with HttpOnly , Secure , and SameSite=Strict flags are more secure. For example, with the HttpOnly flag, the cookies are not accessible through JavaScript, thus making it immune to XSS attacks.

Is Google using JWT? ›

With some Google APIs, you can make authorized API calls using a signed JWT instead of using OAuth 2.0, which can save you a network request.

What is the advantage of using JWT? ›

In the case of JWT, we don't need a database to store the JWT in order to validate them. JWTs have all the information stored inside, which includes the expiration date/time. These are pretty useful because we can validate the token, then use the data within the token (like username) to return the relevant information.

How big is too big for JWT? ›

By default, AM rejects any JWT that expands to more than 32 KiB (32768 bytes), and throws an exception with a message similar to JWT payload decompressed to larger than maximum allowed size .

What are the three main components of a JWT token? ›

Anatomy of a JWT

Figure 1 shows that a JWT consists of three parts: a header, payload, and signature.

Is JWT enough for security? ›

Using JWTs securely goes beyond verifying their signatures. Apart from the signature, the JWT can contain a few other security-related properties. These properties come in the form of reserved claims that can be included in the body of the JWT. The most crucial security claim is the "exp" claim.

What are JWT attacks? ›

What are JWT attacks? 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 problem does JWT solve? ›

The JWT way. JWT, especially when used as a session, attempts to solve the problem by completely eliminating the database lookup. The main idea is to store the user's info in the session token itself! So instead of some long random string, store the actual user info in the session token itself.

Why is JWT better than password? ›

If you were to send username and password with every request, every endpoint then would have to handle authentication logic, which would be a nightmare. Using a JWT, the endpoint can simply verify that it's valid and move on to what it's actually responsible for. JWTs are just one method of authorization.

What is the strongest authentication method? ›

3 Most Secure Authentication Methods
  • One-Time Password (OTP) An OTP and its sibling, time-based one-time passwords (TOTP), are unique temporary passwords. ...
  • Biometrics Authentication. If there's one thing that you always have with you, it's your body. ...
  • Continuous Authentication. ...
  • The Three Factors of Authentication.
Jun 20, 2022

Which is the most powerful authentication method among the four? ›

After traditional password-based login, Multi-Factor Authentication is the most trusted authentication mechanism.

Which is the most powerful authentication method? ›

Biometric Authentication Methods

Biometric authentication relies on the unique biological traits of a user in order to verify their identity. This makes biometrics one of the most secure authentication methods as of today.

Is it safe to store email in JWT? ›

Yes, it is bad practice and a security problem.

Email addresses are PII (personally identifiable information). Like all other PII, email addresses should never be stored unencrypted at rest; doing so is inherently insecure.

Can JWT tokens be hijacked? ›

In this article we will discussing about what vulnerabilities JWT will create and how to avoid from getting your applications hacked. JWTs can be best and secure but it is very secured only if it is used in the right way. Attacks like token stealing, XSS, Middle man attacks are still possible.

Can a JWT be used multiple times? ›

On top of the great gain in terms of saved memory on the server, JWT tokens can be used to authenticate users on multiple applications. To do that, the different applications will need to share the same private key to sign and verify tokens.

How long should a JWT signing key be? ›

A key of the same size as the hash output (for instance, 256 bits for “HS256”) or larger MUST be used with this algorithm. The minimum key length for RSA: A key of size 2048 bits or larger MUST be used with these algorithms.

Do I need a key to decode a JWT? ›

By design, anyone can decode a JWT and read the contents of the header and payload sections. But we need access to the secret key used to create the signature to verify a token's integrity.

What if JWT is intercepted? ›

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.

Can you break a JWT token? ›

It is possible to break an HS256 JWT with a brute-force attack if the key used to sign the JWT is not sufficiently robust. Interestingly, this is an offline attack. Therefore, no requests are sent to the server.

Why should we use JWT instead of cookie based authentication? ›

Encryption is used to keep data private and needs a key (which must be kept a secret) to decrypt it. JWT is a stateless authentication technique based on tokens. Because it's a client-side stateless session, the server doesn't need to rely on a datastore (database) to keep session data.

Is JWT used for frontend or backend? ›

This is referred to as authorization. In this post, I am going to show you how to implement authorization with a frontend (React) and a backend (Node JS) using JSON Web Token (JWT). We will be implementing three API calls to demonstrate the process.

Why use JWT or cookies? ›

Because session cookies are stored in the server's memory, it has the potential of using a lot more resources if the website or app sees a lot of traffic. Because JSON web tokens are stateless, they can potentially save on server resources in many cases.

Why use JWT in API? ›

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 are the disadvantages of using cookies for authentication? ›

Challenges of Cookie-based Authentication

Vulnerable to CSRF: Cookie-based authentications are prone to Cross-site Request Forgery (CSRF) attacks. Hence, they often require additional security postures for protection. Less Mobile-friendly: Cookie-based authentication does not work well with all native applications.

Why is JWT better than API key? ›

Typically, the API key provides only application-level security, giving every user the same access; whereas the JWT token provides user-level access. A JWT token can contain information like its expiration date and a user identifier to determine the rights of the user across the entire ecosystem.

Does FaceBook use cookies or JWT? ›

They use server-side sessions in conjunction with a cookie. The cookie holds an ID, this ID is sent to FaceBook and the server checks the details for the session with that ID. Save this answer.

Does FaceBook use JWT? ›

It provides an entry point: “/auth/facebook” that redirects to FBs and proceeds to the authentication. After that it acquires the AccessToken for the logged user and creates a JWT Token that returns to the client.

What is more secure than JWT? ›

This token implementation is not just safer but is also easier than the JWT. PASETO is more secure than JWT and offers a simpler implementation.

What is the advantage of JWT over session? ›

One of the simplest ways is to return both a session_token and a JWT when a user starts a session. The session_token is a static value that is good for the lifetime of the session (stored server-side), while the JWT has its own, shorter-lived expiry.

Does Google use JWT? ›

With some Google APIs, you can make authorized API calls using a signed JWT instead of using OAuth 2.0, which can save you a network request.

Top Articles
Latest Posts
Article information

Author: Virgilio Hermann JD

Last Updated:

Views: 5972

Rating: 4 / 5 (61 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Virgilio Hermann JD

Birthday: 1997-12-21

Address: 6946 Schoen Cove, Sipesshire, MO 55944

Phone: +3763365785260

Job: Accounting Engineer

Hobby: Web surfing, Rafting, Dowsing, Stand-up comedy, Ghost hunting, Swimming, Amateur radio

Introduction: My name is Virgilio Hermann JD, I am a fine, gifted, beautiful, encouraging, kind, talented, zealous person who loves writing and wants to share my knowledge and understanding with you.