Source: https://www.scottbrady91.com/

Date: 2020-01-15


OpenID Connect is the go to protocol for modern authentication, especially when using Single Page Applications, or client-side applications in general. A library I often recommend to clients is oidc-client, a plain JavaScript library that is part of the IdentityModel OSS project. This handles all of the necessary protocol interactions with an OpenID Connect Provider, including token validation (which strangely some libraries neglect), and is a certified OpenID Connect Relying Party conforming to the implicit RP and config RP profiles.

In this article, we are going to walk through a basic authentication scenario using the Angular CLI and the oidc-client library, during which we will authenticate a user, and then use an access token to access an OAuth protected API. This will use the implicit flow, where all tokens pass via the browser (something to always remember when dealing with code executing on the client, because the application cannot be trusted with features such as long lived tokens, refresh tokens or client secrets).

Recommendations on which flow to use has changed ever so slightly. I recommend sticking with this article for now, and then giving the amendment a read: “Migrating oidc-client-js to use the OpenID Connect Authorization Code Flow and PKCE”. The migration path is trivial.

Angular CLI Initialization

o keep this tutorial simple, we’re going to use the Angular CLI to create our Angular application along with basic routing. If you’re not using the Angular CLI, that’s fine, the OpenID Connect implementation specifics of this article applies to all Angular 4 applications.

So, if you haven’t already, install the Angular CLI as a global package:

npm install -g @angular/cli

We can then create a new application with routing already set up, for now skipping tests:

ng new angular4-oidcclientjs-example –routing -skip-tests

This will initialise everything we need to get started with our app and continue with this tutorial. You should already be able to run the application by navigating to the project (cd angular4-oidcclientjs-example) and running:

ng serve

And now if we navigate to our site (which by default runs on http://localhost:4200), we should see a splash screen with something like “Welcome to the app!”.

Protected Component & Route Guard

Protected Component

So, let’s start by creating a new page/component that requires a user to be authenticated in order to access it. We can generate the component using the Angular CLI command:

ng generate component protected

This will automatically add the component to our app.module, however we will need to manually add this component to our routing so that we can access it. To do this we need to make our app-routing.module look something like this: