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.
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.
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
To pass add the user's access token to the HTTP requests, you can now use the
Previously, you had to use the
HTTP_INTERCEPTORS injection token to register the
AuthInterceptor class provided by the library.
authInterceptor is easier as you'll see in a second.
authInterceptor, simply include it within the
withInterceptors method while registering the HTTP client using
Lastly, to protect the Angular routes, you can use the
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
AutoLoginPartialRoutesGuard to protect the Angular routes.
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
canMatch property of the route.
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!
I appreciate it if you would support me if have you enjoyed this post and found it useful, thank you in advance.