The Techies' pub

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 open the package.json file and update our angular version to RC 4.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

"dependencies":{

"@angular/common":"2.0.0-rc.4",

"@angular/compiler":"2.0.0-rc.4",

"@angular/core":"2.0.0-rc.4",

"@angular/forms":"0.2.0",

"@angular/http":"2.0.0-rc.4",

"@angular/platform-browser":"2.0.0-rc.4",

"@angular/platform-browser-dynamic":"2.0.0-rc.4",

"@angular/router":"3.0.0-alpha.8",

"es6-shim":"0.35.1",

"reflect-metadata":"0.1.3",

"rxjs":"5.0.0-beta.6",

"systemjs":"0.19.26",

"zone.js":"0.6.12"

},

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.

Converting the firstpage into a login page.

Getting our authentication backend up and running so that we could authenticate our user against it and provide a response.

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

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

import{Component,OnInit}from'@angular/core';

import{AuthService}from'../auth.service';

import{Router}from'@angular/router';

@Component({

moduleId:module.id,

selector:'app-firstpage',

templateUrl:'firstpage.component.html',

styleUrls:['firstpage.component.css']

})

exportclassFirstpageComponentimplementsOnInit{

localUser={

username:'',

password:''

}

constructor(privateauth:AuthService,privaterouter:Router){}

ngOnInit(){

}

login(){

let checknow=this.auth.authenticatenow(this.localUser);

checknow.then((res)=>{

if(res){

this.router.navigate(['/second']);

}

else{

console.log('Invalid user');

}

})

}

}

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.

1

ng generate service auth

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.

We use a method called canActivate() which takes in two parameters the ActivatedRouteSnapshot which is the route to be navigated to and the RouterStateSnapshot.

The canActivate() method contains the conditions which are to be checked before the user can be taken to the component pertaining to that route.

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.

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.