Search code examples
angulararchitectureauthorizationreactive-programmingngrx

Verifying tokens in real-time to store in NgRx state?


I have an "authenticated" boolean in my NgRx store keeping track of whether a user is valid or not. But this variable can only be toggled when an action is taken -- logging in, logging out, or sending a POST, for instance -- because I have to verify it on my back-end as well as client-side. Therefor, it cannot be used the way I intend (as a reliable State variable in my Store). I want to know if there is a way to keep this boolean real-time?


Solution

  • Usually you do like that: you have a store for the auth state that has this boolean value with the default value undefined, it means the state isn't clear and all guards and other pieces of the app should wait to the boolean.

    When the app is loading you need to verify the auth state via issuing a request /me or /ping for example and based on its response you set the variable to true / false via related actions.

    Also you should have an interceptor that knows if a request was declined due to expired / wrong auth state and this interceptor also sets the variable to true / false via related actions.