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.
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.
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.
For further information check out the docs or even better this super useful guide with examples, explanations, and resources for RxJS.