How do you secure JWT tokens in your front-end applications? (2024)

Last updated on Mar 16, 2024

  1. All
  2. Front-End Development

Powered by AI and the LinkedIn community

1

Choose a secure storage option

2

Use short expiration times

3

Use token revocation and blacklisting

Be the first to add your personal experience

4

Use HTTPS and secure headers

Be the first to add your personal experience

5

Use libraries and frameworks

Be the first to add your personal experience

6

Here’s what else to consider

JWT tokens are a popular way to authenticate and authorize users in web applications. They are compact, self-contained, and stateless, meaning they can be easily transmitted and verified without relying on a server-side session. However, JWT tokens also pose some security challenges, especially in front-end applications where they are exposed to the browser. In this article, you will learn how to secure JWT tokens in your front-end applications by following some best practices and using some tools and libraries.

Key takeaways from this article

  • Implement secure storage strategies:

    Safeguard your JWT tokens by selecting the correct storage option and then securing it with methods like Content-Security-Policy for XSS and sameSite cookies for CSRF.

  • Specify signing algorithms:

    To prevent unauthorized access, explicitly set the list of accepted signing algorithms for your JWT tokens, including avoiding the insecure 'NONE' algorithm.

This summary is powered by AI and these experts

  • Qian Wan Software Engineer
  • Christopher Hoult Working with SMEs, Start-Ups and…

1 Choose a secure storage option

One of the most important decisions you have to make is where to store your JWT tokens in the browser. There are three common options: local storage, session storage, and cookies. Each one has its pros and cons, but none of them is completely safe from attacks. Local storage and session storage are vulnerable to cross-site scripting (XSS) attacks, where malicious scripts can access and steal your tokens. Cookies are vulnerable to cross-site request forgery (CSRF) attacks, where malicious requests can use your tokens without your consent. To mitigate these risks, you should choose a storage option that suits your use case, use secure and http-only flags for cookies, and implement anti-CSRF measures.

Add your perspective

Help others by sharing more (125 characters min.)

  • Qian Wan Software Engineer
    • Report contribution

    Yes choosing a secure storage is important. But you don't want people to think local storage or cookies are insecure because of XSS and CSRF attacks. There are many types of mitigation here ranging from using CSP for XSS, sameSite cookies, a server validation for CSRF. Also, we're missing one of the more popular techniques, which is to store it in MEMORY and pair it with some refresh token mechanism in cookies. In the end, your objective is not to choose a secure storage option to start, but to choose the right type of storage and THEN SECURE IT.

  • Hatem Soliman Frontend Engineer | UI/UX Design | Digital Marketing | Teacher
    • Report contribution

    As a software developer, it's vital to understand the specific security requirements & context of the application being developed. While selecting a secure storage option for JWT tokens is crucial, it's equally important to implement a multi-layered security approach, including input validation, authentication, & authorization mechanisms. Regular security audits are necessary to identify & address vulnerabilities, alongside staying updated with security best practices & emerging threats. Educating users about security measures such as logging out, avoiding suspicious links, and keeping devices up to date can also mitigate risks. By considering these aspects, developers can enhance application security & protect sensitive data effectively.

    Like

    How do you secure JWT tokens in your front-end applications? (21) 1

Load more contributions

2 Use short expiration times

Another way to secure your JWT tokens is to use short expiration times. This means that your tokens will become invalid after a certain period of time, reducing the window of opportunity for attackers to use them. You can set the expiration time in the payload of your JWT token, using the exp claim. The value of the exp claim should be a numeric date in seconds since the epoch. For example, if you want your token to expire in 15 minutes, you can set the exp claim to the current time plus 900 seconds. However, using short expiration times also means that you have to refresh your tokens more often, which can affect the user experience and the performance of your application.

Add your perspective

Help others by sharing more (125 characters min.)

Load more contributions

3 Use token revocation and blacklisting

Sometimes, you may need to invalidate your JWT tokens before they expire. For example, if a user logs out, changes their password, or reports a security breach, you want to revoke their tokens and prevent them from being used again. However, JWT tokens are stateless, meaning that they do not depend on a server-side session or database to check their validity. Therefore, you need to implement a token revocation and blacklisting mechanism in your application. This can be done by using a separate storage, such as a database or a cache, to keep track of the tokens that have been revoked or blacklisted. Then, you need to check this storage every time you verify a token, and reject it if it is on the list.

Add your perspective

Help others by sharing more (125 characters min.)

4 Use HTTPS and secure headers

Another essential aspect of securing your JWT tokens is to use HTTPS and secure headers. HTTPS is a protocol that encrypts the communication between your browser and your server, preventing anyone from intercepting or tampering with your data. Secure headers are additional information that you can send with your requests and responses, to instruct the browser how to handle your data. For example, you can use the Content-Security-Policy header to restrict the sources of scripts, styles, and images that can be loaded on your page, reducing the risk of XSS attacks. You can also use the Strict-Transport-Security header to enforce HTTPS on your site, preventing downgrade attacks.

Add your perspective

Help others by sharing more (125 characters min.)

5 Use libraries and frameworks

The last tip to secure your JWT tokens is to use libraries and frameworks that can help you with the implementation and management of your tokens. There are many libraries and frameworks available for different languages and platforms, that can handle the creation, verification, storage, refreshment, and revocation of your tokens. For example, if you are using React as your front-end framework, you can use react-jwt-auth or react-redux-jwt-auth to integrate JWT authentication in your application. These libraries provide components, hooks, actions, reducers, and middleware that can simplify your code and handle the token logic for you.

Add your perspective

Help others by sharing more (125 characters min.)

Load more contributions

6 Here’s what else to consider

This is a space to share examples, stories, or insights that don’t fit into any of the previous sections. What else would you like to add?

Add your perspective

Help others by sharing more (125 characters min.)

  • Christopher Hoult Working with SMEs, Start-Ups and Scale-Ups to scale their tech
    • Report contribution

    Make sure you make the list of accepted signing algorithms explicit.NONE is a valid algo, and will let an attacker breeze right through...

    Like

    How do you secure JWT tokens in your front-end applications? (30) How do you secure JWT tokens in your front-end applications? (31) 7

Front-end Development How do you secure JWT tokens in your front-end applications? (32)

Front-end Development

+ Follow

Rate this article

We created this article with the help of AI. What do you think of it?

It’s great It’s not so great

Thanks for your feedback

Your feedback is private. Like or react to bring the conversation to your network.

Tell us more

Report this article

More articles on Front-end Development

No more previous content

  • How can CSS-in-JS improve your front-end development workflow? 440 contributions
  • How can CSS preprocessors and frameworks help you create unique styles? 284 contributions
  • How can you improve your code quality and standards with linters and formatters? 302 contributions
  • How do you keep your service workers scripts up to date? 117 contributions
  • How do you use a CSS preprocessor? 179 contributions
  • How do you design a front-end mockup? 164 contributions
  • What's the best front-end framework for your project? 192 contributions
  • How do you balance reliability and compatibility with innovation in front-end development? 136 contributions
  • How do you balance simplicity and flexibility with CSS frameworks? 60 contributions
  • How do you use hooks with React? 155 contributions
  • How can you get certified in front-end development? 121 contributions
  • How do you create a front-end security audit checklist? 73 contributions
  • How do you learn about Progressive Web Apps and Service Workers? 42 contributions
  • How can you overcome front-end development challenges in the current market? 125 contributions
  • How can you improve your front-end projects with design principles and user research? 76 contributions

No more next content

See all

More relevant reading

  • Front-end Development What are the best practices for storing and sending JWT tokens in the browser?
  • Web Development How can SameSite cookies prevent Cross-Site Request Forgery attacks?
  • Front-end Design How do you debug front-end security and privacy issues?
  • Web Development How can you secure your web app's performance?

Are you sure you want to delete your contribution?

Are you sure you want to delete your reply?

How do you secure JWT tokens in your front-end applications? (2024)

FAQs

How do you secure JWT tokens in your front-end applications? ›

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.

How to secure JWT in frontend? ›

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.

How do I make my JWT token secure? ›

Best Ways to Securely Implement JWTs
  1. Use strong algorithms like HMAC-SHA256 or RSA to sign and encrypt your tokens. ...
  2. Set an expiration time for the JWT to limit its validity period. ...
  3. Set refresh token features to extend the session duration, which allows users to fetch new JWT tokens for an extended period of time.

How to use JWT in a web application? ›

To support JWT authentication:
  1. Add the following to the security definition in your API config, which follows the OpenAPI 2.0 security scheme: See more code actions. ...
  2. Add a security section at either the API level to apply to the entire API, or at the method level to apply to a specific method. See more code actions.

How do I make my tokens secure? ›

Token Best Practices
  1. Keep it secret. ...
  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: Technically, once a token is signed, it is valid forever—unless the signing key is changed or expiration explicitly set.

How to store tokens in front end? ›

There are three common options: local storage, session storage, and cookies. Each one has its pros and cons, but none of them is completely safe from attacks. Local storage and session storage are vulnerable to cross-site scripting (XSS) attacks, where malicious scripts can access and steal your tokens.

How to secure JWT in a single page application? ›

React state variables will be assigned to default values when the app is refreshed or opened in a new tab, so if the default values are null, when the app is refreshed or opened in a new tab it will be set to null, so when we set the JWT in state variable it will disappear, so the user need to log in each time the app ...

Does JWT put your web app at risk? ›

As you've learned, JWT vulnerabilities can compromise the integrity of web applications, leading to unauthorized access, data breaches, and system compromise.

Where should the JWT token be stored? ›

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.

How to secure token in client side? ›

Using Web Workers to handle the transmission and storage of tokens is the best way to protect the tokens, as Web Workers run in a separate global scope than the rest of the application.

Why is JWT not secure? ›

The biggest problem with JWT is the token revoke problem. Since it continues to work until it expires, the server has no easy way to revoke it. Below are some use cases that'd make this dangerous.

How does JWT security work? ›

Here is how JWT can be used in an authentication flow: A user provides their credentials (e.g., username and password) and sends them to the server. The server validates the credentials. If they are correct, the server generates a JWT containing the user's information (in a claim) and signs it with a secret key.

Is JWT obsolete? ›

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.

How do I stop JWT from being stolen? ›

  1. don't store them in local or session storage, only in memory.
  2. keep their lifetime short, for example 5min.
  3. put multiple identifiers i to the token, for example the users ip address. If the request containing the token comes from another ip, reject it.
May 18, 2024

How do I secure my front end API? ›

You can use a third-party service, such as Google reCAPTCHA, to implement a CAPTCHA on your front-end app. This will ensure that only genuine users can access your API. These are some of the best practices for securing your backend API endpoints on the front-end.

How to secure a JWT token in React? ›

Storing JWT tokens securely, using HTTPS, implementing token expiration, using refresh tokens, including a CSRF token, and validating the JWT signature are all important steps to take to secure JWT tokens in React applications.

How to encrypt JWT token in JavaScript? ›

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);

Top Articles
“15-Minute City” and Elderly People: Thinking about Healthy Cities
Liquidity Provider: How to Become a Liquidity Provider and Earn Fees - FasterCapital
Fernald Gun And Knife Show
Kostner Wingback Bed
Jennifer Hart Facebook
What spices do Germans cook with?
Craigslist Vans
Missed Connections Inland Empire
Booknet.com Contract Marriage 2
Toyota gebraucht kaufen in tacoma_ - AutoScout24
What Happened To Father Anthony Mary Ewtn
The Haunted Drury Hotels of San Antonio’s Riverwalk
Savage X Fenty Wiki
What is the difference between a T-bill and a T note?
Cvb Location Code Lookup
Itziar Atienza Bikini
Sni 35 Wiring Diagram
Officialmilarosee
EASYfelt Plafondeiland
Kcwi Tv Schedule
Like Some Annoyed Drivers Wsj Crossword
Talkstreamlive
Mythical Escapee Of Crete
Anonib Oviedo
Mineral Wells Skyward
Arrest Gif
Publix Near 12401 International Drive
Cowboy Pozisyon
Is Henry Dicarlo Leaving Ktla
Infinite Campus Asd20
Rs3 Bring Leela To The Tomb
Jail Roster Independence Ks
The Bold and the Beautiful
Ripsi Terzian Instagram
About | Swan Medical Group
Audi Q3 | 2023 - 2024 | De Waal Autogroep
Metro By T Mobile Sign In
AsROck Q1900B ITX und Ramverträglichkeit
Ashoke K Maitra. Adviser to CMD's. Received Lifetime Achievement Award in HRD on LinkedIn: #hr #hrd #coaching #mentoring #career #jobs #mba #mbafreshers #sales…
Gun Mayhem Watchdocumentaries
Reese Witherspoon Wiki
Alston – Travel guide at Wikivoyage
Cabarrus County School Calendar 2024
Interminable Rooms
R/Gnv
Human Resources / Payroll Information
UNC Charlotte Admission Requirements
Muni Metro Schedule
All Buttons In Blox Fruits
Mytmoclaim Tracking
Treatise On Jewelcrafting
Latest Posts
Article information

Author: Jonah Leffler

Last Updated:

Views: 5674

Rating: 4.4 / 5 (65 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Jonah Leffler

Birthday: 1997-10-27

Address: 8987 Kieth Ports, Luettgenland, CT 54657-9808

Phone: +2611128251586

Job: Mining Supervisor

Hobby: Worldbuilding, Electronics, Amateur radio, Skiing, Cycling, Jogging, Taxidermy

Introduction: My name is Jonah Leffler, I am a determined, faithful, outstanding, inexpensive, cheerful, determined, smiling person who loves writing and wants to share my knowledge and understanding with you.