Authentication in NGXS
Recently Brandon Roberts did a GREAT talk on Authentication in NGRX on NGCONF. After all, authentication is something that almost all our applications have to have. After seeing the talk, I wanted to take some of the same ideas and apply those to NGXS.
First, let’s define our state model and our actions. We need to define our ‘state’ model along with 2 actions, ‘login’ and ‘logout’.
In this example, we are going to use JWT for authentication. In our state model, let’s track the JWT token and the username.
Next, let’s write our state class that will include:
- A selector that will select the token from the store
- A login action method that will invoke the authentication service and set the token
- A logout action method that will invoke the authentication service and remove our state
Once we’ve created the model, actions and state all we need to do is wire up the state to our
In a typical JWT setup, you need to store your token in the
localstorage. Luckily for us, NGXS comes with a storage plugin out of the box. We can hook this plugin up and tell it to track our token in local storage.
Now that we have everything wired together, we want to setup some restrictions that will prevent users from visiting pages if they aren’t logged in. We can easily accomplish this with a router guard provided by Angular.
In this guard, we select out our token from the store using our token selector. If the token is null, it would be a falsey preventing us from visiting the page. Let’s make sure to define the
AuthGuard in the
A common action you want to take is when a user logs out, we want to actually redirect the user to the login page. We can use our action stream to listen to the
Logout action and tell the router to go to the login page.
And that’s it!