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.

Angular

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…).

Pre-requisites

We will go step by step to proceed with auth0 authentication.

Setup Auth0 Account

Create Angular App

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

Angular

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.

Angular

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

Angular

Angular

But we need to wire up the main event called ‘authenticated’ in constructor to get the Token like below.

Angular

Finally we add the auth.service.ts reference in app.module.ts file under @NgModule decorator in providers array.

Angular

Once authenticated, auth0 will post token back to client side so that we have to specify the url in allowed callback URL under client -> settings tab. In this case we give ‘http://localhost:4200’

Now if you run http://localhost: 4200 in your browser you will be able to see login button, click on that you will get the login widget like below

Angular

That’s it. You can find the source code here.

I always welcome your comments/feedback about this post.