JWT Authentication — Best Practices and When to Use (2024)

One of the most used authentication standards in web applications is the JSON Web Token standard. It is mostly used for authentication, authorization, and information exchange.

JSON Web tokens are made of three parts separated by dots (.) — and look like this typically: xxxxx.yyyyy.zzzzz. These correspond to the Header, the Payload, and the Signature. You can learn more about JWT tokens here.

And before using them and continuing to read this article, you might want to check the advantages compared to the session authentication method. You can learn more about JWTs vs. Sessions here.

When to Use JWT Authentication?

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.

Authorization

A server built on JWT for authorization will create a JWT when a client logs in. This JWT is signed, so any other party can’t alter it.

Each time the client has access to protected resources, the server will verify that the JWT’s signature matches its payload and header to determine that the JWT is valid.

Then if the JWT is successfully verified, it can grant or deny access to the resource.

Data Exchanges

JWT is also a great way to secure information transmission between parties — two servers, for example — and because you can verify the validity of the token (signature, structure, or the standards claimed in the JWT).

When Not to Use JWT Authentication?

Revocable Tokens

JWT doesn’t require any lookup of the database, so revoking them before the expiration is quite difficult.

Revocation is very important in many cases.

For example, when logging out users or banning users, or changing permissions or passwords instantly, if the token hasn't been revoked, it might be possible for the user to continue to make requests even if this user no longer has the required authorization to do so.

Sensitive Information

JWT is usually signed to protect against data manipulation or alteration. With this, the data can be easily read or decoded.

So, you can’t include sensitive information such as the user’s record or any identifier because the data is not encrypted.

Cookie Size Factor

The size of a JWT is greater than the size of a session token. And this can quickly increase linearly as you add more data to the JWT. And because you need to send the JWT at each request, you're increasing the payload size. This can become heavily complex if there is a low-speed internet connection.

JWT: Best Practices

1) JWT as Access Token

JWT can be used as an access token to prevent unwanted access to a protected resource. They're often used as Bearer tokens, which the API will decode and validate before sending a response.

Authorization: Bearer <token>

2) Refresh Tokens Logic with JWT

How do you get a new access token if this one is expired? The natural first idea is to log in again. But from a User Experience point, this can be quite painful.

JWT can be used as refresh tokens; these tokens are used to retrieve a new access token.

For example, when a client requests a protected resource and receives an error, which can mean that the access token has expired, the client can be issued a new access token by sending a request with a refresh token in the headers or the body.If the refresh token is valid, a new access token will be created and sent as a response.

Note that the refresh token is obtained at authentication and has a bigger lifetime.

3) Which Signing Algorithm to Use?

Interestingly enough, JWT can be signed using many different algorithms. But let’s quickly talk about the alg value in the JWT header. When it’s decoded:

The alg value in JWT headers simply tells you how the JWT was signed. For example, with an alg value of RS512.

RS512 => RS 512 where RS is the signature algorithm and SHA-512 is the hashing algorithm.

SHA-512 will produce a 512-bits hash while SHA-256 will produce a 256-bit hash. And each of these algorithms gives you 50% of their output size of security level. This means that, for example, SHA-512 will provide you with 256-bits security.

In any case, make sure to use a minimum of 128-bit security.

4) Expiration, Issued Time, and Clock Skew

JWTs are hard to revoke when they are created. Most of the time, you’ll have to wait until expiry. That’s why you should use a short expiration time.

Additionally, you can implement your own revocation system.

JWT comes with a time-based claim iat — issued at. It can be used to reject tokens that are too old to be used by the resource server.And clock skew specifies the allowed time difference (in seconds) between the server and the client clocks when verifying exp and nbf time-based claims. The default recommended default value is 5.

5) JWT Signature

The last part of a JWT is the signature, which is simply a MAC (or Message Authentication Code). This signature is created by the server using a secret key. This secret key is an important part of the JWT signature.

There are two things to respect to decrease the probability of a secret key leaking or a successful brute force attack:

  • Keep the secret key secret
  • The minimum key length must be equal to the size of bits of the hash function used along with the HMAC algorithm.

    "A key of the same size as the hash output (for instance, 256 bits for "HS256") or larger MUST be used with this algorithm." - JSON Web Algorithms (RFC 7518), 3.2 HMAC with SHA-2 Functions

6) Where to Store the Tokens?

The easiest ways to store a token on the client side are localStorage and sessionStorage. However, both are vulnerable to XSS attacks, and sessionStorage is cleaned if the browser is closed.

A better, secure way is to store JWT in cookies. Cookies are not accessible via JavaScript, they can’t be read and written, and interestingly, they are automatically sent to the server.

7) Always Use HTTPS

One of the main benefits of HTTPS is that it comes with security and trust. HTTP path and query parameters are encrypted when using HTTPS.

Then, there is no risk of someone intercepting the request, particularly the token in transit. These types of attacks are commonly called MitM (man in the middle) attacks that can be successful on compromised or insecure networks.

Conclusion

This article discussed JWT and some best practices to fully use its potential.

JWT is simply an authentication standard with its pros and cons. Thus, knowing some best practices can really help you use JWT better.

JWT Authentication — Best Practices and When to Use (2024)

FAQs

When should you use JWT? ›

JWTs are well-suited for server-to-server or microservice-to-microservice communication scenarios within a backend architecture. In this context, JWTs serve as a means of securely transmitting information between services for authorization and authentication purposes.

What is the best practice for JWT duration? ›

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. You should avoid giving your tokens expiration times in days or months.

Why use JWT instead of basic auth? ›

JWT is preferred over any other authentication method because of certain distinct benefits it presents. Developers opt for JWT as these tokens are self-contained and don't ask for any effort to collect info about the user.

When to use OAuth2 vs JWT? ›

OAuth and JWT are both standards for authorization and authentication. OAuth is suitable for delegating user authorization, accessing third-party applications, and session management. JWT is suitable for stateless applications, API authentication, and server-to-server authorization.

Why avoid JWT? ›

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.

What are the limitations 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.

Is JWT good for API authentication? ›

Any API that requires authentication can easily switch over to JWT's authorization. With JWT authorization, you get a user-based authentication. Once the user is authenticated, the user gets a secure token that they can use on all systems. The management of the user (and therefore the token) is centralized.

What is the safest JWT algorithm? ›

To avoid these security vulnerabilities, it is crucial to follow good coding practices when working with JWT authentication: Always sign the JWT token: Use a secure signing algorithm, such as HMAC or RSA, to sign the token with a secret or private key. This ensures the integrity and authenticity of the token.

How big is too big for a 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 .

Is JWT obsolete? ›

In May 2023, Adobe announced the deprecation and end of life of Service Account (JWT) credentials. This means that any of your integrations or custom applications using a Service Account (JWT) credential will need to migrate to the new OAuth Server-to-Server credential before January 27, 2025.

Why use JWT instead of session? ›

Choosing between JWT and session-based authentication depends on your application's specific needs. If you prioritize statelessness and scalability, JWT might be your go-to. For traditional applications where immediate control over sessions is crucial, session-based authentication holds the upper hand.

What is the best alternative to JWT? ›

Paseto, which stands for Platform-Agnostic Security Tokens, is a specification for secure stateless tokens. It provides a modern and better alternative to JWT, addressing some of its inherent vulnerabilities and emphasizing secure defaults and ease of implementation.

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 certain 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.

Should I use JWT for login? ›

JWT is usually signed to protect against data manipulation or alteration. With this, the data can be easily read or decoded. So, you can't include sensitive information such as the user's record or any identifier because the data is not encrypted.

How to use JWT authentication with REST API? ›

Procedure
  1. Make sure that the JWT authentication is enabled for REST APIs by setting the value of servlet. jwt. auth. ...
  2. The incoming HTTP request for REST API call must contain the request header “Authorization” with scheme “Bearer” followed by JWT. The signature of the token and expiration date is verified by the system.

What are JWTs good for? ›

JWTs can be used in various ways: Authentication: When a user successfully logs in using their credentials, an ID token is returned. According to the OpenID Connect (OIDC) specs, an ID token is always a JWT.

What is the main purpose of JWT? ›

A JSON web token(JWT) is JSON Object which is used to securely transfer information over the web(between two parties). It can be used for an authentication system and can also be used for information exchange. The token is mainly composed of header, payload, signature. These three parts are separated by dots(.).

Should you use a JWT as an API key? ›

However, you can't control all API use; API keys are likely to leak; HTTPS is not always possible; and so on. With JWT, because the token is hashed / encrypted, it comes with a more secure methodology that is less likely to be exposed.

Top Articles
Montessori Education — Montessori Northwest
3 Big Problems With Social Security (and What You Can Do to Prepare) | The Motley Fool
This website is unavailable in your location. – WSB-TV Channel 2 - Atlanta
Places 5 Hours Away From Me
Chicago Neighborhoods: Lincoln Square & Ravenswood - Chicago Moms
Obor Guide Osrs
Frank Lloyd Wright, born 150 years ago, still fascinates
Sissy Transformation Guide | Venus Sissy Training
877-668-5260 | 18776685260 - Robocaller Warning!
Mawal Gameroom Download
Elden Ring Dex/Int Build
Was sind ACH-Routingnummern? | Stripe
What is the surrender charge on life insurance?
2021 Lexus IS for sale - Richardson, TX - craigslist
Dumb Money
ExploreLearning on LinkedIn: This month&#39;s featured product is our ExploreLearning Gizmos Pen Pack, the…
7 Fly Traps For Effective Pest Control
Youravon Comcom
Epro Warrant Search
Swedestats
Conan Exiles: Nahrung und Trinken finden und herstellen
Cbssports Rankings
Aol News Weather Entertainment Local Lifestyle
Red Cedar Farms Goldendoodle
If you have a Keurig, then try these hot cocoa options
Shadbase Get Out Of Jail
Craigslist Roseburg Oregon Free Stuff
Craigslist Alo
Koninklijk Theater Tuschinski
Victory for Belron® company Carglass® Germany and ATU as European Court of Justice defends a fair and level playing field in the automotive aftermarket
Is Holly Warlick Married To Susan Patton
Homewatch Caregivers Salary
What Time Is First Light Tomorrow Morning
The Mad Merchant Wow
Hellgirl000
Omaha Steaks Lava Cake Microwave Instructions
Easy Pigs in a Blanket Recipe - Emmandi's Kitchen
Lovein Funeral Obits
Lonely Wife Dating Club בקורות וחוות דעת משתמשים 2021
Man Stuff Idaho
Trivago Sf
Bekah Birdsall Measurements
Autum Catholic Store
Luciane Buchanan Bio, Wiki, Age, Husband, Net Worth, Actress
Gotrax Scooter Error Code E2
Gli italiani buttano sempre più cibo, quasi 7 etti a settimana (a testa)
Unblocked Games - Gun Mayhem
My Gsu Portal
Bradshaw And Range Obituaries
Diesel Technician/Mechanic III - Entry Level - transportation - job employment - craigslist
Palmyra Authentic Mediterranean Cuisine مطعم أبو سمرة
Shad Base Elevator
Latest Posts
Article information

Author: Melvina Ondricka

Last Updated:

Views: 6131

Rating: 4.8 / 5 (68 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Melvina Ondricka

Birthday: 2000-12-23

Address: Suite 382 139 Shaniqua Locks, Paulaborough, UT 90498

Phone: +636383657021

Job: Dynamic Government Specialist

Hobby: Kite flying, Watching movies, Knitting, Model building, Reading, Wood carving, Paintball

Introduction: My name is Melvina Ondricka, I am a helpful, fancy, friendly, innocent, outstanding, courageous, thoughtful person who loves writing and wants to share my knowledge and understanding with you.