JWT Authentication in the Frontend: Enhancing Security in Web Applications (2024)

In this lesson, we will learn how we can use the JWT token in our front end to authenticate the user and prevent unauthorized access to our Web application/website.

In my previous blog, I created a API server that provides us with the endpoints for login, and as soon as we log in we get the data of the logged-in user along with the access token and refresh token. That we can use in our front end to authenticate our identity to the server. In this Blog, I will be using React JS for my front end.

Let’s have a revision.

What is JWT?

JWT stands for JSON Web Token. It is an open standard (RFC 7519) for securely transmitting information between parties as a JSON object. JWTs are commonly used for authentication and authorization in web applications and APIs.

This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

A JWT is composed of three parts: a header, a payload, and a signature.

  1. Header — The header consists of two parts: the algorithm used to sign the token such as HMAC SHA256 or RSA, and the type of token, which is JWT in this case.
  2. Payload — The payload contains the claims. The claims are entity specific such as we can pass user_id or username or anything we want.
  3. Signature — The signature is formed by combining the encoded header, encoded payload, and a secret key known only to the server. It is used to verify the integrity of the token and to ensure that it is not been tampered.

How does JWT Work?

The typical flow used when working with JWT token involves —

  1. User Authentication — First the user Authenticate itself to the server by passing the credentials.
  2. Token Generation — As soon as the user has been authenticated a token is been generated which contains some user details as a payload that will be need by the front end as well as back end to perform validations.
  3. Token Storage — This part is where the server has sent the token to the front end in response to the login request and the front end stores it in the local Storage or in session.
  4. Making Request — Whenever the client makes a request to the back end servers it will pass the JWT access token in the header to authenticate its identity to the server. This is the main purpose of the JWT.
  5. Token Verification — The server then validates the request headers i.e the JWT access token and if the token is valid then the server gives the access to the requested resources and if the token is not valid then it will return 401 status code i.e user unauthenticated.

What does jwt expired mean?

For Improving the security, there is an additional feature in JWT where we can define the expiration time i.e after a specific period of time the access token will not be valid. We cannot use the JWT access token after it is expired. We need to generate a new one to access the server.

For this we use refresh access token that is responsible for getting the new access token for the client.

Recommended by LinkedIn

JWT : Logout, expire and prolongation Thomas LEDUC 7 years ago
The Essentials of JSON Web Tokens: From Structure to… Denys S. 4 days ago
Understanding Access Tokens and Refresh Tokens Mohiuddin Monzil 2 weeks ago
Now we will develop our Front end for using the JWT access token.

We will be creating a login form for seeing how to use JWT in front end. So lets first create a react app, I will be using Vite for creating my React app.

npm create vite@latest 

This will then ask you for the project name that you want to give and then select react and simple javascript. This will create a folder that will contain the app. Then we need to install all the necessary packages.

cd project_namenpm i 

After creating our React app now we will make a form for log in. That will let the user access the server. And when the user login using the username and password, the back end will give the access along with the access token and the refresh token.

So first lets create our Login form.

App.js

import axios from "axios";function App(){const [user, setUser] = useState(null);const [username, setUsername] = useState("");const [password, setPassword] = useState("");const handleSubmit = async(e)=>{e.preventDefault(); try{ const response = await axios.post("/api/login",{username,password}) setUser(response.data)}catch(error){ console.log(error)}return(<div className="container">{user ? (<div className="login"> <form onSubmit={handleSubmit}> <span className="formTitle">Lama Login</span> <input type="text" placeholder="username" onChange={(e) => setUsername(e.target.value)} /> <input type="password" placeholder="password" onChange={(e) => setPassword(e.target.value)} /> <button type="submit" className="submitButton"> Login </button> </form></div>:<span>User has been loggedIn </span>}</div>)} 

App.css

.container { font-family: "Quicksand", sans-serif;}.login{ width: 200px; height: 200px; padding: 20px; position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; border: 1px solid lightgray; border-radius: 10px;}.formTitle { color: teal; font-weight: bold;}.submitButton { width: 100px; padding: 10px; border: none; border-radius: 10px; background-color: teal; color: white; cursor: pointer;} 

Now we will write the code for after login functionality in the return of the function App(). After login the user with the privilege can perform the delete operation. After adding the functionality the App.js file will look like this.

function App() { const [user, setUser] = useState(null); const [username, setUsername] = useState(""); const [password, setPassword] = useState("");const handleSubmit = async (e) => { e.preventDefault(); try { const res = await axios.post("/login", { username, password }); setUser(res.data); } catch (err) { console.log(err); } }; const handleDelete = async (id) => { setSuccess(false); setError(false); try { await axios.delete("/users/" + id, { headers: { authorization: "Bearer " + user.accessToken }, }); setSuccess(true); } catch (err) { setError(true); } };return ( <div className="container"> {user ? ( <div className="home"> <span> Welcome to the <b>{user.isAdmin ? "admin" : "user"}</b> dashboard{" "} <b>{user.username}</b>. </span> <span>Delete Users:</span> <button className="deleteButton" onClick={() => handleDelete(1)}> Delete John </button> <button className="deleteButton" onClick={() => handleDelete(2)}> Delete Jane </button> {error && ( <span className="error"> You are not allowed to delete this user! </span> )} {success && ( <span className="success"> User has been deleted successfully... </span> )} </div> ) : ( <div className="login"> <form onSubmit={handleSubmit}> <span className="formTitle">Lama Login</span> <input type="text" placeholder="username" onChange={(e) => setUsername(e.target.value)} /> <input type="password" placeholder="password" onChange={(e) => setPassword(e.target.value)} /> <button type="submit" className="submitButton"> Login </button> </form> </div> )} </div> );} 

When we login using the login form we get the user data along with the access token and the refresh token. We pass the access token when we perform a delete request to the server. But there is something that can go wrong, that is the access token can get expire, that will raise error so we need to check the access token before passing it to the server and if it has been expired we need to get the new access token using the refresh token.

const axiosJWT = axios.create() axiosJWT.interceptors.request.use( async (config) => { let currentDate = new Date(); const decodedToken = jwt_decode(user.accessToken); if (decodedToken.exp * 1000 < currentDate.getTime()) { const data = await refreshToken(); config.headers["authorization"] = "Bearer " + data.accessToken; } return config; }, (error) => { return Promise.reject(error); } );const handleDelete = async (id) => { setSuccess(false); setError(false); try { await axiosJWT.delete("/users/" + id, { headers: { authorization: "Bearer " + user.accessToken }, }); setSuccess(true); } catch (err) { setError(true); } }; 

By doing this it will handle the access token expiring issue and get you the new access token prior to sending the request to the server.

JWT Authentication in the Frontend: Enhancing Security in Web Applications (2024)

FAQs

JWT Authentication in the Frontend: Enhancing Security in Web Applications? ›

It is an open standard (RFC 7519) for securely transmitting information between parties as a JSON object. JWTs are commonly used for authentication and authorization in web applications and APIs. This information can be verified and trusted because it is digitally signed.

How does JWT work in frontend? ›

JWT work by using a stateless and token-based approach to authentication. This means that the server does not need to store any session data or cookies for each user or client, which reduces the load and complexity of the server.

What is JWT in web security? ›

JWT signature

This mechanism provides a way for servers to verify that none of the data within the token has been tampered with since it was issued: As the signature is directly derived from the rest of the token, changing a single byte of the header or payload results in a mismatched signature.

How are JWTs typically used in web applications? ›

JWT authorization uses a JWT to represent the user's identity and access rights. The JWT is usually generated by the authentication server after the user logs in and contains the user's identity and access rights. The JWT is then sent with every API request as a bearer token in the authorization header.

What are the benefits of JWT authentication? ›

Stateless Authentication: JWTs are self-contained and carry all the necessary information, which eliminates the need for a server-side session store. Scalability: Being stateless, JWTs are easily scalable across multiple servers as there's no need to share session data.

How to secure a JWT token in frontend? ›

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 main purpose of JWT? ›

JSON Web Token (JWT) authentication is a stateless method of securely transmitting information between parties as a JavaScript Object Notation (JSON) object. It is often used to authenticate and authorize users in web applications and APIs.

What are the three types of JWT? ›

Types of JWT
  • JSON Web Signature (JWS) – The content of this type of JWT is digitally signed to ensure that the contents of the JWT are not tampered in transit between the sender and the receiver. ...
  • JSON Web Encryption (JWE) – The content of this type of JWT is digitally encrypted.

How secure is JWT authentication? ›

JWTs are self-contained, which means that all the information needed to validate the token is contained within the token itself. This makes them easy to use and implement, as well as secure since they are signed and can be verified by the receiving party.

Is JWT best for authentication? ›

When to Use JWT. JWT is ideal for: Stateless authentication: Perfect for web and mobile apps where you don't want to store session information server-side. Secure data transmission: When you need to send information securely between parties.

How to use JWT in a web app? ›

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.

How to explain JWT in an interview? ›

JWT (JSON Web Token) is a standard format for securely transmitting information between two parties. It is often used with web APIs and mobile applications and can be used to securely store user credentials, authentication information, and other sensitive data.

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.

What is the disadvantage of JWT? ›

Cons of JWT:

No revocation: Once a JWT is issued, it cannot be revoked. This means that if a user's credentials are compromised, the JWT will remain valid until it expires. Security vulnerabilities: JWTs can be susceptible to certain security vulnerabilities, such as timing attacks or algorithmic weaknesses.

When should JWT be used? ›

Here are some scenarios where JSON Web Tokens are useful: Authorization: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token.

Is JWT more secure than 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.

How does JWT algorithm work? ›

The issuer appends the JWT header and payload with the secret key, and hashes the result using SHA256, creating a signature. The recipient uses their copies of the secret key, JWT header and payload in the same way to reproduce the signature, checking to see if they match.

Where should the JWT token be stored in frontend? ›

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.

How do you use JWT in react frontend? ›

JWT Authentication in React
  1. Step 1: Create the Project. So let's create our demo app with create-react prompt: npx create-react-app react-jwt-auth. ...
  2. Step 2: Creating RouteGuard Component. First I'll create folder called components, and add RouteGuard. ...
  3. Step 3: Creating Home and Login Page.
Feb 10, 2022

How does JWT token work in Web API? ›

The Identity Provider generates a JWT certifying user identity, and the resource server decodes and verifies the authenticity of the token using the public key. Since the tokens are used for authorization and authentication in future requests and API calls great care must be taken to prevent security issues.

Top Articles
Get the Azure AD token by Using the Postman
How Much to Tip Movers - Shepherd International Movers
Evil Dead Movies In Order & Timeline
Diario Las Americas Rentas Hialeah
Cold Air Intake - High-flow, Roto-mold Tube - TOYOTA TACOMA V6-4.0
Fully Enclosed IP20 Interface Modules To Ensure Safety In Industrial Environment
Victoria Secret Comenity Easy Pay
Tlc Africa Deaths 2021
Crime Scene Photos West Memphis Three
CSC error CS0006: Metadata file 'SonarAnalyzer.dll' could not be found
PGA of America leaving Palm Beach Gardens for Frisco, Texas
Fredericksburg Free Lance Star Obituaries
The Murdoch succession drama kicks off this week. Here's everything you need to know
Michaels W2 Online
Gino Jennings Live Stream Today
Vrachtwagens in Nederland kopen - gebruikt en nieuw - TrucksNL
Bridge.trihealth
Craigslist Pinellas County Rentals
Moving Sales Craigslist
Putin advierte que si se permite a Ucrania usar misiles de largo alcance, los países de la OTAN estarán en guerra con Rusia - BBC News Mundo
How to Grow and Care for Four O'Clock Plants
27 Paul Rudd Memes to Get You Through the Week
Ihub Fnma Message Board
Panola County Busted Newspaper
Apparent assassination attempt | Suspect never had Trump in sight, did not get off shot: Officials
Labcorp.leavepro.com
Schooology Fcps
Little Einsteins Transcript
Evil Dead Rise - Everything You Need To Know
+18886727547
134 Paige St. Owego Ny
Inmate Search Disclaimer – Sheriff
Learn4Good Job Posting
Bt33Nhn
Top-ranked Wisconsin beats Marquette in front of record volleyball crowd at Fiserv Forum. What we learned.
Is Arnold Swansinger Married
ENDOCRINOLOGY-PSR in Lewes, DE for Beebe Healthcare
Jail View Sumter
Stanley Steemer Johnson City Tn
Gfs Ordering Online
Barstool Sports Gif
11 Best Hotels in Cologne (Köln), Germany in 2024 - My Germany Vacation
Southwest Airlines Departures Atlanta
Scythe Banned Combos
Enr 2100
Sandra Sancc
Booknet.com Contract Marriage 2
Headlining Hip Hopper Crossword Clue
5103 Liberty Ave, North Bergen, NJ 07047 - MLS 240018284 - Coldwell Banker
Hy-Vee, Inc. hiring Market Grille Express Assistant Department Manager in New Hope, MN | LinkedIn
Escape From Tarkov Supply Plans Therapist Quest Guide
Latest Posts
Article information

Author: Dong Thiel

Last Updated:

Views: 6265

Rating: 4.9 / 5 (59 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Dong Thiel

Birthday: 2001-07-14

Address: 2865 Kasha Unions, West Corrinne, AK 05708-1071

Phone: +3512198379449

Job: Design Planner

Hobby: Graffiti, Foreign language learning, Gambling, Metalworking, Rowing, Sculling, Sewing

Introduction: My name is Dong Thiel, I am a brainy, happy, tasty, lively, splendid, talented, cooperative person who loves writing and wants to share my knowledge and understanding with you.