Angular 2 – Authentication using the new router.

Hi Friends,
Hope you are all well. The new ‘improved’ router has been released and I made a post on it last week. Many of my friends who read that requested for an updated authentication post using that router and so this is a response to all my friends who requested the same.

Let’s begin.

A screencast of this post

 

The complete code for this tutorial is available here.

A quick recap of my previous post. We just created a simple app which had two screens and saw how we could use the new router to navigate between those two. We will continue from where we left off.

You could grab a copy of the code from our last post here.

Let’s open the package.json file and update our angular version to RC 4.

Run npm install once again to get our angular versions updated.

What we’ll be doing is simple. We have two components firstpage and secondpage. We will convert one of them into a login page. Upon entering the credentials the user will be able to view the other page. If not we will block the user from accessing the second page.

Now that we have our workflow before us. I’ll divide it into three.

  1. Converting the firstpage into a login page.
  2. Getting our authentication backend up and running so that we could authenticate our user against it and provide a response.
  3. Writing a route-guard mechanism that will enable us to route the user or navigate the user based on the response from the backend when he logs in.

Part one:

In order to beautify the code a little bit I will be making use of a design framework called materialize.css (This is optional, on the other hand feel free to use whatever design framework you are familiar with).

Open up index.html and add the below lines in the head section.

Now that we have added the deps, just open up firstpage.component.html file and add the below code.

Open up firstpage.component.css and add the below code.

That’s it. Now that our login page has been designed. Let’s go ahead and wire this up to our back-end.

Part two:

Now open up firstpage.component.ts and modify it as shown below.

Okay. In the above code we just have method called login() and in this we are calling up another method called authenticatenow() which is present in our service. Then depending on the response from this we either navigate to the second page or stay in the first page.

Hold on a second, did you say service ? Yup. Our asynchronous call happens there. So let’s create a new service using the below command.

this will generate a new file called auth.service.ts. Open it up and add the below code.

The above code is not new for us guys. In fact, it’s exactly the same code as we saw in our last angular 2 – authentication post. We are making a XHR to our backend REST Api to authenticate the user and then upon success we take the jwt-token¬†that is returned and set it in our browser’s localStorage with the key auth_key.

Part 3:

Now let’s write the real authentication code. Open up a new file called authmanager.ts and add the below code to it.

Let’s break this down.

  1. We use a method called canActivate() which takes in two parameters the ActivatedRouteSnapshot which is the route to be navigated to and the RouterStateSnapshot.
  2. The canActivate() method contains the conditions which are to be checked before the user can be taken to the component pertaining to that route.
  3. Flow of the code – Here we are just checking whether an auth_key is present in the local storage, if it is present then we conclude that the user is authenticated and allow him to navigate to the second page.
  4. We also check certain conditions whenever the destination route is the login page. i.e., If the user is logged in and he tries to navigate back to the login page then he is not allowed to do so.

Our Auth Manager is ready. But we need to tell our routes configuration to make use of this right.? So let’s go ahead and open up our routes.ts file and modify it as shown below.

I have simply made use of the canActivate property while specifying the routes. Whenever the routes are invoked this makes sure that the conditions specified while traversing the routes are satisfied. (In our case the AuthManager).

Okay, so far, so good. Now we have to bootstrap our service and our authmanager to our main.ts file.

Open up index.ts and add the below lines of code so that the files looks as shown below.

Open up main.ts file and modify it as shown below.

We are done now.. Phew.. That was a lot of code.. :)

You could grab a copy of the back-end from here.

Start the back-end server using the below command.

Ensure that the DB is up and running before you give the above command.

Then start your angular 2 app using the below command.

If everything goes fine you should now see a wonderful app with perfect route level authentication.

If not kindly clone my repo from here and try out the same.

(Please watch the video so that you could get a bit more insight on this.)

Hope this helped you friends. Kindly share this post with others so that it helps them too.

Thanks for reading guys. Peace.. :)

 

  • Ali Kolahdoozan

    return new Promise((resolve) =>

    Shall we replace it with an Observable ?.