Angular 4 Authentication With Auth0

Before getting into this, we need to understand how auth0 authentication works. In the traditional approach we store user related information in the server as a session to track the authentication related permission. But later we came to the concept of JWT (JSON Web Token) stateless authentication since user state will not be maintained in server side.

In JWT stateless authentication approach, once the user is authenticated token will be generated at server side then that will be passed to client side to store it in browser’s local storage so that in subsequent requests we can call the api with this stored JWT.

JWT comprises some sort of useful information with respect to user such as Id, Name, Roles, etc. Let’s dive into the implementation of the same.

Third party authentication provider Auth0 has various sets of pricing models but they do have a free plan as well with 7000 users registration and two social media accounts (Facebook, Github, Google, Twitter, etc…).

Once done with above step, click on clients tab from left tab navigation

Create new Client with app name and client type as single page app

If you want to show social login in login widget then enable corresponding social login through clicking on connections -> Social.

Up to now we’re ok to go ahead.

Create Angular App

First, let’s create angular 4 app with cli using

ng new ng4Auth0 (generates the angular app structure)

Then, we need to install two important libraries of Auth0 to deal with JWT and login widget.

npm install –g angular2-jwt auth0-lock --save

we need to give the reference of lock0 script file in an index.html.

In app.module.ts file, we need to wire up the reference of Angular2-JWT module as given below in an exported function way.

Here we tell to Angular2-JWT that our default token name would be ‘id_token’ after user is authenticated then generated token will be stored with id_token in local storage.

Then we specify that exported function in providers array of @NgModule decorator.

Earlier it was working just by simply giving the below reference and adding that into providers' array would make sense, but in recent versions of angular2-jwt this didn’t work out. So we proceed with the above approach.

Now we create service.ts file which is solely responsible for communicating with Auth0. Now we can grab the client Id and Domain name from http://auth0.com under your client tab click on the recently created client app.

There you can get client id and domain name. With that you can create auth0-lock object which helps to display login UI.

We need to give the reference of Auth0Lock to avoid from exception thrown like below