Angular — Authentication with Auth0 and NGRX

Stuart Tottle
6 min readNov 4, 2018

--

My interpretation of how auth0 can be integrated with NGRX in an Angular Application.

I’ve implemented Auth0 in several Angular applications over the years and wanted to document a way of achieving this.

Overview

I’ve created an Angular module which could be imported into any angular application that wraps the Auth0 library into an Angular Service and stores authentication details in NGRX.

This article is structured as follows:

  1. Using the auth0-js library to authenticate a user
  2. Storing, renewing and retrieving the access token in the NGRX store
  3. Router guards using data from the NGRX store
  4. HTTP interceptors to add the bearer token to HTTP requests
  5. Redux dev tools example

Final code is on GitHub

I’ve also created an NPM package

1. Using the auth0-js library to authenticate a user

I’m using an npm package that wraps selected methods from the auth0-js library and returns values from methods as an observable.

It makes use of the authorize method that redirects the user to the Auth0 hosted login page, which can be customised to suit the layout and style of your application. The package handles the authorisation callback and emits the authentication information (decoded hash) as an observable.

The library also stores a redirect URL in local storage which can be retrieved when the user has returned to your site to redirect the user after login.

2. Storing, renewing and retrieving the access token in the NGRX store

I’ve attempted to split the store into small collections (actions, effects and reducers) that have a responsibility for

  • Showing the login page, handling authorisation and logout
  • Obtaining user information
  • Renewing access token (check session)
  • Checking users’ authentication status and populating the NGRX store
  • Resetting password

Showing the login page, handling authorisation and logout

Aim: to show the login page and how to handle the authentication callback to add the access token and the time it will expire to the NGRX store (and local storage) - also to log the user out to revoke their access token.

Dispatch the Authorize action to display the sign-up or login form. The action has two parameters for the redirectUrl (where do you want to navigate the user after they have been authorised) and the auth0 authorize options to display the sign-up/login form and other items. This will take the user to the hosted login form and return the user to the specified callback page after they have entered the correct details.

The callback component dispatches the AthenticationComplete action which handles the Auth0 authorization callback and dispatches the AuthenticationSuccess action to save the Authentication Details in the NGRX store (including the access token).

You could also listen to the AuthenticationSuccess action in your application effects and use the payload to perform various actions including

  • Redirecting the user when they return to your application (example)
  • Getting user data from your own API
  • Connecting to a WebSocket.

Use the selectAuthenticationData or selectIsAuthenticated selectors to retrieve authentication details from the NGRX store (including the access token).

Error: You can handle errors in your application by listening to the AuthenticationError action in your effects and/or using the selectAuthenticationError selector.

To log the user out, dispatch the Logout action to revoke their access token and clear the NGRX store and local storage.

Obtaining user information

Aim: to obtain user information and claims from Auth0 after the user is authenticated.

The GetUserInfoStart action is dispatched when the AuthenticationSuccess action is dispatched, and it will obtain information and claims about the logged in user based on the requested scopes from Auth0. You shouldn’t need to dispatch this from within your application.

The users’ information can be retrieved from the store using the selectUserInfo selector.

Renewing Access Token (check session)

Aim: to renew the access token at regular intervals to ensure the user has not logged out on another device or if it is about to expire.

The ScheduleSessionCheck action is dispatched when the AuthenticationSuccess action is dispatched and starts a timer to perform a session check either just before the access token is due to expire or at an interval (set by options when importing the module)

Check the session at regular intervals, as a user could be accessing your application from multiple devices or you could have multiple applications that use the same user account.

Checking users’ authentication status and populating the store

Aim: to check local storage for valid authentication information and renew the access token when a user returns to your site.

Dispatch the CheckAuthenticationStatus action in the app.component to check local storage for an access token and whether it has expired.

The UserIsAuthenticated action is dispatched if the user’s access token is valid, and this will dispatch the CheckSessionStart action to renew the user’s access token to ensure the NGRX store has the latest authentication details (and local storage).

The UserIsNotAuthenticated action is dispatched when the user is not authenticated to allow your application to dispatch further actions if required.

Changing a user’s password

Aim: to ask the user for their email address so the user can be sent an email with a link to change their password

Dispatch the ChangePasswordStart action with the relevant options to send a change password email to the user using changePassword in the Auth0-js library. The response is saved in the NGRX store and can be retrieved using the selectChangePasswordResponse selector.

3. Route Guard

The router guard checks the NGRX store as to whether the user is authenticated. It will also dispatch the Authorize action to show the login form if the user is not authenticated and save the Url the user was trying to access so the user can be redirected after login.

Package Link: auth-guard

4. HTTP Interceptor

The HTTP interceptor will intercept all HTTP request to check if the user is authenticated and add the authorisation header with the bearer access token from the NGRX store.

Package Link: auth-interceptor

5. Redux dev tools example

Action Hygiene is important as the redux dev tools should tell a story to other developers of what is happening in your application. Below are some screen shots of the redux dev tools for when a user

  • Is not authenticated
  • Has just logged in
  • Has returned to the site and has a valid access token in Local Storage

Is not authenticated

The application checks the store for a valid access token and clears local storage if it is not valid.

User not authenticated

Has just logged in

The application still checks local storage when the user has returned to your site, so it still thinks the user is not authenticated, but the callback component then dispatches the AuthenticationComplete action and the user’s authentication details are stored in NGRX (and local storage), a session check is scheduled and the user info is retrieved. The application also redirects the user to the route they were trying to access before they logged in.

After login

Is returning to the site and has a valid access token in Local Storage

The application finds a valid access token and dispatches a session check to update the access token and obtain the user info.

Returning user

Conclusion

This is my interpretation of how a library could be created to manage authentication in Angular, so please let me know if you have any questions, comments or observations about the article, but raise code issues on the GitHub repo.

The package I have created is available on npm (@stottle-platform/ngx-auth-wrapper-ngrx), and I have implemented the package in my own application (stottle.co.uk), so feel free to browse the code repo on GitHub.

There is also an NGRX example from Auth0 from which I drew some inspiration.

--

--

Responses (2)