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
Know Top 10 Fastest-Growing Cryptocurrencies of Jan 2022
Bybit Review (2023) – ☑️ Pros and Cons Revealed.
AMC Theatre - Rent A Private Theatre (Up to 20 Guests) From $99+ (Select Theaters)
English Bulldog Puppies For Sale Under 1000 In Florida
Instructional Resources
Tyson Employee Paperless
Www.politicser.com Pepperboy News
Videos De Mexicanas Calientes
Computer Repair Tryon North Carolina
Infinite Campus Parent Portal Hall County
Globe Position Fault Litter Robot
3656 Curlew St
2135 Royalton Road Columbia Station Oh 44028
O'reilly's Auto Parts Closest To My Location
Calmspirits Clapper
Seattle Rpz
Arre St Wv Srj
Mals Crazy Crab
Divina Rapsing
Officialmilarosee
Jang Urdu Today
Zack Fairhurst Snapchat
Isaidup
Highmark Wholecare Otc Store
Best Boston Pizza Places
Olivia Maeday
Hannah Palmer Listal
D2L Brightspace Clc
6892697335
Criterion Dryer Review
Goodwill Of Central Iowa Outlet Des Moines Photos
Penn State Service Management
Stephanie Bowe Downey Ca
Publix Christmas Dinner 2022
Kaiser Infozone
Tmj4 Weather Milwaukee
Mississippi State baseball vs Virginia score, highlights: Bulldogs crumble in the ninth, season ends in NCAA regional
Vanessa West Tripod Jeffrey Dahmer
Snohomish Hairmasters
Aliciabibs
Spectrum Outage in Genoa City, Wisconsin
Davis Fire Friday live updates: Community meeting set for 7 p.m. with Lombardo
Xxn Abbreviation List 2023
Florida Lottery Claim Appointment
How to Connect Jabra Earbuds to an iPhone | Decortweaks
Kaamel Hasaun Wikipedia
Missed Connections Dayton Ohio
Craigslist Psl
David Turner Evangelist Net Worth
Edict Of Force Poe
Tamilyogi Cc
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.