Angular — How to automatically log out the user after a JWT expires (2024)

Angular — How to automatically log out the user after a JWT expires (2)

So you read a few tutorials, perhaps dived a bit into the documentation and after some quality coding time you’ve got a nice first Angular application with all there is to desire as a beginner: Slick design, material components, protected routes using guards and a login system as part of a backend made with NodeJS? or was it Spring?

Everything seems to work, until, wait, the JSON Web Token expired but you’re still looking at that protected view. Most likely is no biggie, the user can’t really interact with the backend, because well, the token is expired, but for sure that’s a detail that must be polished. Enter RxJS.

If you coded this up, odds are you touched some RxJS already and saw a bunch of Observables around. If not really, here is a quick definition from the project’s website:

RxJS is a library for reactive programming using Observables, to make it easier to compose asynchronous or callback-based code.

I will assume you have the Auth logic in a dedicated auth service. This is because the user status cannot depend on a single component.

Without further ado, let’s look at some code.

In this sample implementation, we have a basic 3 steps Auth flow, where the user logs in (the application stores somewhere the JWT), the user interacts with the backend using protected routes/views (Http requests are intercepted and an Authorization header is appended to them) and finally, the user logs out or the JWT expires, whichever comes first.

Login logic

From our login component, we send the user credentials to the backend. If everything is okay, we call then the storeUserData() method, which saves the JWT and username in the Session Storage, calculates the remaining time for this token to expire and finally calls our expirationCounter() to take over the job.

Angular — How to automatically log out the user after a JWT expires (3)

JWT expiration counter logic

Let’s now deal with the actual waiting-for-the-token-to-expire-to-react. First, we want to get rid of previous subscriptions. We do that by calling unsubscribe on, forgive the redundancy, the Subscription property we defined in the class.

Then we create a new one, let’s start it by passing a fake Observable ‘of(null)’, from which we’ll pipe a delay of exactly the amount of time there’s left for the JWT to expire and finally, when this occurs, we call our logout method and rout the user to the login page.

Angular — How to automatically log out the user after a JWT expires (4)

Logout logic

In the logout method, we first make sure we unsubscribed from any ongoing subscription, e.g. the user logged out before the session expired, and finally we clear class properties and Session Storage from all session-related info.

Angular — How to automatically log out the user after a JWT expires (5)

For further information check out the docs or even better this super useful guide with examples, explanations, and resources for RxJS.

Angular — How to automatically log out the user after a JWT expires (2024)

FAQs

What to do when a JWT token is expired? ›

If the JWT has expired, prompt the user to log in again and remove the JWT from storage. If the JWT has not expired, make the API call as normal. If the API call returns a 401 Unauthorized response, it means the JWT has expired or is invalid.

How to handle JWT token expiration in Angular? ›

  1. Step 1: Setting Up JWT Decode. Install the JWT Decode package with: npm install jwt-decode. ...
  2. Step 2: Creating an Interceptor. Generate a token interceptor using: ng generate interceptor token. ...
  3. Step 3: Registering the Interceptor. In app. ...
  4. Step 4: Implementing the Interceptor. ...
  5. Step 5: Refreshing or Redirecting.
Nov 20, 2023

How to implement auto logout in Angular? ›

Smart Auto-Logout in Angular with RxJS: Enhancing Security and User Experience
  1. Step 1: Setting Up the Angular Project. ...
  2. Step 2: Installing RxJS. ...
  3. Step 3: Implementing Auto-Logout Logic. ...
  4. Step 4: Integrating Auto-Logout with User Interface. ...
  5. Step 5: Testing the Auto-Logout Feature.
May 3, 2024

Top Articles
5 Ways to Recover your Data from Damaged CDs
Identify and Control Black Spot
Tiny Tina Deadshot Build
Fan Van Ari Alectra
Promotional Code For Spades Royale
Plaza Nails Clifton
T&G Pallet Liquidation
Smokeland West Warwick
Umn Biology
Select Truck Greensboro
Osrs Blessed Axe
Thotsbook Com
Blog:Vyond-styled rants -- List of nicknames (blog edition) (TouhouWonder version)
Rosemary Beach, Panama City Beach, FL Real Estate & Homes for Sale | realtor.com®
Gon Deer Forum
Amc Flight Schedule
Jinx Chapter 24: Release Date, Spoilers & Where To Read - OtakuKart
Troy Bilt Mower Carburetor Diagram
Lonesome Valley Barber
St. Petersburg, FL - Bombay. Meet Malia a Pet for Adoption - AdoptaPet.com
Delaware Skip The Games
Eine Band wie ein Baum
Ein Blutbad wie kein anderes: Evil Dead Rise ist der Horrorfilm des Jahres
Juicy Deal D-Art
Katie Sigmond Hot Pics
Craigslist Lewes Delaware
All Obituaries | Verkuilen-Van Deurzen Family Funeral Home | Little Chute WI funeral home and cremation
Milwaukee Nickname Crossword Clue
Margaret Shelton Jeopardy Age
WRMJ.COM
Pulitzer And Tony Winning Play About A Mathematical Genius Crossword
Sandals Travel Agent Login
Summoners War Update Notes
CohhCarnage - Twitch Streamer Profile & Bio - TopTwitchStreamers
101 Lewman Way Jeffersonville In
FREE Houses! All You Have to Do Is Move Them. - CIRCA Old Houses
DIY Building Plans for a Picnic Table
Solve 100000div3= | Microsoft Math Solver
Linabelfiore Of
Dying Light Nexus
Second Chance Apartments, 2nd Chance Apartments Locators for Bad Credit
11301 Lakeline Blvd Parkline Plaza Ctr Ste 150
Mid America Clinical Labs Appointments
About My Father Showtimes Near Amc Rockford 16
Top 40 Minecraft mods to enhance your gaming experience
Ouhsc Qualtrics
Lebron James Name Soundalikes
Used Sawmill For Sale - Craigslist Near Tennessee
Mikayla Campinos Alive Or Dead
Bluebird Valuation Appraiser Login
Glowforge Forum
Laurel Hubbard’s Olympic dream dies under the world’s gaze
Latest Posts
Article information

Author: Carmelo Roob

Last Updated:

Views: 5752

Rating: 4.4 / 5 (65 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Carmelo Roob

Birthday: 1995-01-09

Address: Apt. 915 481 Sipes Cliff, New Gonzalobury, CO 80176

Phone: +6773780339780

Job: Sales Executive

Hobby: Gaming, Jogging, Rugby, Video gaming, Handball, Ice skating, Web surfing

Introduction: My name is Carmelo Roob, I am a modern, handsome, delightful, comfortable, attractive, vast, good person who loves writing and wants to share my knowledge and understanding with you.