Configuring angular-auth-oidc-client with the new functional APIs

profile
Tim Deschryver
timdeschryver.dev

The last versions of Angular included new APIs to configure your application(s) in a functional way. Think of the new functional guards, and the new APIs for the HTTP client including functional interceptors. Of course, there are also standalone components, which introduced EnvironmentProviders.

The latest version of angular-auth-oidc-client (v16.0.0) includes new functionality to support the new Angular APIs. In this blog post, I'll show you how to use them.

format_quote

If you prefer to just see the code, you can find the sample application here. You can also run this example to see it in action.

provideAuth link

Let's start with configuring the authentication module, which is the first step towards using the library.

Instead of using the AuthModule, you can use the provideAuth method to configure the authentication flow. Pass it the same configuration options as you would with the AuthModule (the config object is the same) while invoking the provideAuth method.

authInterceptor link

To pass add the user's access token to the HTTP requests, you can now use the authInterceptor function. Previously, you had to use the HTTP_INTERCEPTORS injection token to register the AuthInterceptor class provided by the library. Using authInterceptor is easier as you'll see in a second.

To use authInterceptor, simply include it within the withInterceptors method while registering the HTTP client using provideHttpClient.

autoLoginPartialRoutesGuard link

Lastly, to protect the Angular routes, you can use the autoLoginPartialRoutesGuard method. Using the guard secures the route, and ensures that the user is authenticated before the route is activated. A route that is protected by this guard will redirect the user to the login page if she's not authenticated.

With the previous version, you had to use the class-based guards AutoLoginAllRoutesGuard or AutoLoginPartialRoutesGuard to protect the Angular routes.

Warning

The AutoLoginAllRoutesGuard guard is not migrated to the new functional APIs. This is because the guard is deprecated and will be removed in a future version.

To protect a route, append autoLoginPartialRoutesGuard to the canActivate or canMatch property of the route.

Putting it all together link

When putting all of this together, you'll end up with something like this:

You can a working example here.

To have an overview of all the new APIs, check out the migration guide.

Feel free to update this blog post on GitHub, thanks in advance!

Join My Newsletter (WIP)

Join my weekly newsletter to receive my latest blog posts and bits, directly in your inbox.

Support me

I appreciate it if you would support me if have you enjoyed this post and found it useful, thank you in advance.

Buy Me a Coffee at ko-fi.com PayPal logo

Share this post