Authentication And Authorization In Angular - Part Twelve

Not often, but in most of the applications, we use authentication and authorization. In this article, we will explore the following topics.

  • JSON Web Tokens (JWT)
  • Stateless Authentication
  • How to Protect Routes in Angular Apps?
  • Redirect the User to “Login” or “Access Denied” page.
  • Show/Hide Elements Depending Upon the Authentication Status of the User
  • How to Get Currently Logged In User?
  • How to Consume Protected API Endpoints?

If you’ve not seen my Angular series yet, you should start your journey from here.

Architecture

Before we get into the mechanics of implementing Authentication and Authorization, let’s have a quick look at high-level architecture. So, let’s start with Authentication.

In order to build authentication, on the client, we need to build the login page and on the server, we should build an API Endpoint to validate the user. When the user clicks on the login button, our Angular app calls this API Endpoint and passes the username and password. Now, on the server, we’re going to validate these credentials and if they are valid, we’re going to return what we called a JSON WEB TOKEN (JWT). This token is basically a JSjson object that includes certain attributes about the logged in user. And we use it to identify the user on the client and also on the server.

Authentication And Authorization In Angular 

Now we get these JSON WEB TOKEN objects on the Client and then we need to store it somewhere persistent, so it can exist across session restarts. So if the user closes your browser and then opens it again, the token still should be there and we use the localStorage for that. So almost all modern browsers have a simple storage per website and they also provide the API for storing key value pairs into this storage. So we’re going to use this native API to store our JSON Web Token inside the browsers’ local storage.

Authentication And Authorization In Angular 

Now on the client, we can use this token to identify the user. For example,

  • We can display their name on the navigation bar.
  • We can show/hide parts of the page.
  • We can prevent access to certain routes (if they don’t have the valid token).

This is how we work with these tokens on the client. Now let’s suppose, the user wants to get the list of orders from the server and this list is only available to an authenticated user. So, on the server, we have an API Endpoint (/api/orders) and in order to get the list of orders on the client, we should include the jwt in the request header. And then on the server, we should extract this token validated. And if it is valid it will return the list of orders otherwise it should return the unauthorized response. The response with the status code is 401.

Authentication And Authorization In Angular 

This is the big picture.

JSON Web Tokens (JWT)

Now let’s explore JWT in more detail. Look here we have a Debugger for working with JSON Web Tokens. Here, we also have a bunch of libraries to work with JSON web tokens. So as we already discussed we need to work with these tokens both on the client and on the server that’s why we have lots of libraries for different languages and platforms. So, on the front-end, we’ll use the library for Angular and for the backend we need a different library depending upon which platform or language you’re working in.

So, come to the Debugger tab in jwt.io where you see 2 tabs - Encoded & Decoded. So Encoded has a really long string of JSON web token.

Authentication And Authorization In Angular 

So, this is the token that the server has sent to the client upon successful authentication. Note the color coding here. This token has 3 parts. The header is indicated by red, the payload is indicated by purple, and the digital signature is indicated by blue. And we can see each of these parts on the decoded tab as well. One more thing - this token is not encrypted but encoded with BASE 64 algorithm. So, we don’t have any sensitive information here. If you paste this string into any Base 64 decoder, you can see the content.

Now, let’s come to the Decoded section.

Authentication And Authorization In Angular 

Here, we have the header which is basically a JSON object with 2 property algorithms, HS256 and type with JWT, this is the standard header. And we don’t have to be worry about it. Below that we have payload which is once again JSON object with a few properties, these properties are attributes about the user. So here we have sub for subject name and admin. This sub property identifies the subject of jwt which is the user's id and this object contains some content of the client. Now we can include a few other attributes here as well, a few other properties. And these are the properties we need to know in a lot of places in the application because we’re going to send this web token within the client and the server by including these properties in the token, we don’t have to go into the database to find let us say the name of the user everytime there is a request. So that’s why we have few basic properties of the user in the payload of the JSON web token. Now below that we have a signature, we use this signature to prevent a malicious user from modifying any of the header and payload properties. Because this signature is based on a secret that exists on the server.

Authentication And Authorization In Angular 

So unless your malicious user can compromise your server, it will not be able to generate the digital signature for a token.

Now let’s see how this digital signature is constructed. Basically we get the header encoded using base64 algorithm and concatenate it with payload encoded using base64. And then we use the secret to encrypt that long string using HMACSHA256 algorithm. So there are 2 interesting points here, first is this digital signature is based on the content of the JSON web token so if we change the payload the signature needs to be regenerated. In other words, a malicious user can’t come back here and simply modify any of the payload property for someone else JSON web token and if he modify any of the payload property he need to regenerate the digital signature. And the 2nd interesting point here that this signature is generated through the secret that exists only on the server. So unless the hacker knows this secret, he can’t generate this digital signature.

Let’s see it in action. Let’s change the value of any payload property.

 Authentication And Authorization In Angular 

Now look here the payload encoded string is also changed.

Authentication And Authorization In Angular 

So every time we modify the header or payload of the JSON web token, the signature is regenerated. Now we have the good understanding of high level architecture and JSON web token. Now let’s get started to implement authentication and authorization in our application.

Starter Code

So to speed things up, I’ve attached the starter code of Auth-Demo. So we’ll start authentication and authorization in this project. To configure this project to properly work, execute these commands one by one.

  • PS C:\Users\Ami Jan\auth-demo\auth-demo> npm install
  • PS C:\Users\Ami Jan\auth-demo\auth-demo> npm i angular2-jwt --save
  • PS C:\Users\Ami Jan\auth-demo\auth-demo> ng serve

Now when you run this application,

Authentication And Authorization In Angular 

This is what you get. If you go to Login, you’ll navigate to Login page but nothing gonna happen on sign in.

Authentication And Authorization In Angular 

So we’re getting this application and adding authentication and authorization into it. Before getting into the implementation details, let’s review few things of this project. So open app.module.ts. Look here in the imports array, we can see we have few routes.

  1. imports: [  
  2.   BrowserModule,  
  3.   FormsModule,  
  4.   HttpModule,  
  5.   RouterModule.forRoot([  
  6.     { path: '', component: HomeComponent },  
  7.     { path: 'admin', component: AdminComponent },  
  8.     { path: 'login', component: LoginComponent },  
  9.     { path: 'no-access', component: NoAccessComponent }  
  10.   ])  
  11. ]  

Now look at the providers array,

  1. providers: [  
  2.   OrderService,  
  3.   
  4.   AuthService,  
  5.   
  6.   // For creating a mock back-end. You don't need these in a real app.   
  7.   fakeBackendProvider,  
  8.   MockBackend,  
  9.   BaseRequestOptions  
  10. ],  

Here we have OrderService which is a very simple service getting the list of orders from the server. Next we have AuthService which we use to implement login and logout. Now let’s take a look of AuthService.

  1. export class AuthService {  
  2.   constructor(private http: Http) {  
  3.   }  
  4.   
  5.   login(credentials) {   
  6.    return this.http.post('/api/authenticate',   
  7.       JSON.stringify(credentials));  
  8.   }  
  9.   
  10.   logout() {   
  11.   }  
  12.   
  13.   isLoggedIn() {   
  14.     return false;  
  15.   }  
  16. }  

So it is the very simple class that is dependent upon the http service as you can see in class constructor. We’re injecting Http as the dependency to AuthService. Here we have the login() method which is kind of half implemented, which we’ll finish in this complete article. Here we have other methods as well (logout(), isLoggedIn()) and it looks like they are not implemented as well. Now back in app.module.ts, after AuthService we have few providers that are purely implementing mock backend. So you don’t need to add them in the real world application

  1. // For creating a mock back-end. You don't need these in a real app.  
  2. fakeBackendProvider,  
  3. MockBackend,  
  4. BaseRequestOptions 

Now let’s see how we implemented this mock backend. So let’s go to fakeBackendProvider

  1. import { Http, BaseRequestOptions, Response, ResponseOptions, RequestMethod } from '@angular/http';  
  2. import { MockBackend, MockConnection } from '@angular/http/testing';  
  3.   
  4. export function fakeBackendFactory(  
  5.     backend: MockBackend,   
  6.     options: BaseRequestOptions) {  
  7.           
  8.   let token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ik1vc2ggSGFtZWRhbmkiLCJhZG1pbiI6dHJ1ZX0.iy8az1ZDe-_hS8GLDKsQKgPHvWpHl0zkQBqy1QIPOkA';  
  9.       
  10.   backend.connections.subscribe((connection: MockConnection) => {  
  11.     // We are using the setTimeout() function to simulate an   
  12.     // asynchronous call to the server that takes 1 second.   
  13.     setTimeout(() => {  
  14.       //  
  15.       // Fake implementation of /api/authenticate  
  16.       //  
  17.       if (connection.request.url.endsWith('/api/authenticate') &&  
  18.         connection.request.method === RequestMethod.Post) {  
  19.         let body = JSON.parse(connection.request.getBody());  
  20.   
  21.         if (body.email === 'abc@domain.com' && body.password === '1234') {  
  22.           connection.mockRespond(new Response(  
  23.             new ResponseOptions({  
  24.               status: 200,  
  25.               body: { token: token }  
  26.            })));  
  27.         } else {  
  28.           connection.mockRespond(new Response(  
  29.             new ResponseOptions({ status: 200 })  
  30.           ));  
  31.         }  
  32.       }  
  33.   
  34.   
  35.        //   
  36.        // Fake implementation of /api/orders  
  37.        //  
  38.        if (connection.request.url.endsWith('/api/orders') &&   
  39.            connection.request.method === RequestMethod.Get) {  
  40.          if (connection.request.headers.get('Authorization') === 'Bearer ' + token) {  
  41.             connection.mockRespond(new Response(  
  42.               new ResponseOptions({ status: 200, body: [1, 2, 3] })  
  43.          ));  
  44.        } else {  
  45.            connection.mockRespond(new Response(  
  46.              new ResponseOptions({ status: 401 })  
  47.            ));  
  48.        }  
  49.     }  
  50.   
  51.   
  52.     }, 1000);  
  53.   });  
  54.   
  55.   return new Http(backend, options);  
  56. }  
  57.   
  58. export let fakeBackendProvider = {  
  59.     provide: Http,  
  60.     useFactory: fakeBackendFactory,  
  61.     deps: [MockBackend, BaseRequestOptions]  
  62. };  

So here we have exported the function fakeBackendFactory, this function takes 2 parameters, MockBackend and BaseRequestOptions. Don’t be scared by watching the above code, always write the simple code. It doesn't need to be more complex. The above code is just for demonstration.

So here we have declared a variable token and we have set this to a valid JSON web token that extracted from a jwt.io and if you see the comment ‘Fake implementation of /api/authenticate’ in the code. So here we have some basic logic to check the url of the request.

  1. if (connection.request.url.endsWith('/api/authenticate') &&  
  2.   connection.request.method === RequestMethod.Post) {  
  3. }  

So if the url of the request ends with /api/authenticate and the request method is post, that means the client sends the http post request to this endpoint. Here we want to validate the username and password and if they are valid, it will return jwt

  1. if (body.email === 'abc@domain.com' && body.password === '1234') {  
  2.   connection.mockRespond(new Response(  
  3.     new ResponseOptions({  
  4.       status: 200,  
  5.       body: { token: token }  
  6.    })));  
  7. else {  
  8.   connection.mockRespond(new Response(  
  9.     new ResponseOptions({ status: 200 })  
  10.   ));  
  11. }  

In else block the response status should be 400, but it doesn’t really matter here for the purpose of this article. So all this logic is to implement the fake api endpoint like we have here. And after this, we have fake implementation of orders. And here we’re also doing something very similar.

  1. if (connection.request.url.endsWith('/api/orders') &&   
  2.     connection.request.method === RequestMethod.Get) {  
  3.   if (connection.request.headers.get('Authorization') === 'Bearer ' + token) {  
  4.      connection.mockRespond(new Response(  
  5.        new ResponseOptions({ status: 200, body: [1, 2, 3] })  
  6.   ));  
  7. else {  
  8.     connection.mockRespond(new Response(  
  9.       new ResponseOptions({ status: 401 })  
  10.     ));  
  11. }  

As you can see we’re returning 401 status which means Unauthorized.

In the real world application, you’re going to build this logic on the server, not on the client. All these logics are for implementing api endpoint, you can see we’ve wrapped all the code in setTimeout() to simulate asynchronous call to the server.

  1. setTimeout(() => {  
  2. }, 1000);  

And one last thing, at the end of this file we have exported an object called fakeBackendProvider. Note that this object has 3 properties

  1. export let fakeBackendProvider = {  
  2.     provide: Http,  
  3.     useFactory: fakeBackendFactory,  
  4.     deps: [MockBackend, BaseRequestOptions]  
  5. };  

Provide, useFactory, deps (represents dependencies).

So what are these dependencies? Let’s go back to the app.module.ts. Here in the providers array earlier in the article about CRUD operation with Fake Http Service, we use the provider array like this

  1. providers: [  
  2.   OrderService,  
  3.   
  4.   AuthService,  
  5.   
  6.   { provide: ErrorHandler, useClass: AppErrorHandler },  
  7.   
  8.   // For creating a mock back-end. You don't need these in a real app.   
  9.   fakeBackendProvider,  
  10.   MockBackend,  
  11.   BaseRequestOptions  
  12. ]  

So with this object, we told angular that wherever you need to provide ErrorHandler instead use this class AppErrorHandler. So this is what we called provider object. Now here in this article, we’re using useFactory instead of using useClass and we set it to a function that will create an instance of provide class

  1. export let fakeBackendProvider = {  
  2.     provide: Http,  
  3.     useFactory: fakeBackendFactory,  
  4.     deps: [MockBackend, BaseRequestOptions]  
  5. };  

So here we’re telling  Angular, that hey, whenever you use an instance of Http class, use this useFactory function. And we already know that Factory methods and Factory functions create objects. So here fakeBackendFactory is a function that will create an instance of Http class. And you can see the last line of the fakeBackendFactory method, we’re returning an instance of Http class with relevant arguments.

  1. return new Http(backend, options);  

And here backend is MockBackend and options is BaseRequestOptions, so we take these arguments and modify them to respond to those fake api endpoints. And one last thing,

deps: [MockBackend, BaseRequestOptions]

These are the dependencies of our factory function. And Angular needs to know this before it can call factory function. It was all about the starter code and the fakeBackend.

Implementing Login

So let’s see how to implement login. So open the login.component.ts

  1. export class LoginComponent {  
  2.   invalidLogin: boolean;   
  3.   
  4.   constructor(  
  5.     private router: Router,   
  6.     private authService: AuthService) { }  
  7.   
  8.   signIn(credentials) {  
  9.     this.authService.login(credentials)  
  10.       .subscribe(result => {   
  11.         if (result)  
  12.           this.router.navigate(['/']);  
  13.         else    
  14.           this.invalidLogin = true;   
  15.       });  
  16.   }  
  17. }  

It is the very basic component. In the constructor we have 2 dependencies, router and authService. Here in the signIn method, we get the credentials object which is the value behind our form. Just to refresh your memory, go to login.component.html and on the top we have form element and here we have set it to the variable ngForm and then submit this form f.value to signIn method.

  1. <form class="form-signin" #f="ngForm" (ngSubmit)="signIn(f.value)">  
  2.   <h2 class="form-signin-heading">Please sign in</h2>  
  3.   <div *ngIf="invalidLogin" class="alert alert-danger">Invalid username and/or password.</div>  
  4.   <label for="inputEmail" class="sr-only">Email address</label>  
  5.   <input type="email" id="inputEmail" name="email" ngModel class="form-control" placeholder="Email address" required autofocus>  
  6.   <label for="inputPassword" class="sr-only">Password</label>  
  7.   <input type="password" id="inputPassword" name="password" ngModel class="form-control" placeholder="Password" required>  
  8.   <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>  
  9. </form>  

So the value of this form is an object with 2 properties, email and password. Now back in our login.component.ts,  here in the singIn() method we call the login() method of authService and pass the credentials and this returns an Observable and then we subscribe to that

  1. signIn(credentials) {  
  2.   this.authService.login(credentials)  
  3.     .subscribe(result => {   
  4.       if (result)  
  5.         this.router.navigate(['/']);  
  6.       else    
  7.         this.invalidLogin = true;   
  8.     });  
  9. }  

If the result is true, it navigates to the Home page otherwise we set invalidLogin to true and we use this field to toggle the validation error. And in login.component.html, you can see here we have a div for displaying the message and we render this invalid username or password.

  1. <div *ngIf="invalidLogin" class="alert alert-danger">  
  2. Invalid username and/or password.  
  3. </div>  

Now, we don’t change any code here in signIn() method but let’s take a deeper look in authService. So let’s go to the authService,

  1. login(credentials) {   
  2.  return this.http.post('/api/authenticate',   
  3.     JSON.stringify(credentials));  
  4. }  

Here in the login() we’re sending the post request to this endpoint and in the body of the request we’re including the credentials which is an object with 2 properties, email and password. As you know, this post() returns an Observable of Response. But in our Login(), we don’t want to expose the Response object. I just want to return true or false. So here we use the map operator and then we convert it to true or false. So we map this observable get the response and then display the response object in the console. And here with http method it automatically displays in the form of json so you don’t need to manually mention the .json() here

  1. login(credentials) {   
  2.  return this.http.post('/api/authenticate',   
  3.     JSON.stringify(credentials))  
  4.     .pipe(  
  5.       map(response => {  
  6.         console.log(response);  
  7.       })  
  8.     );  
  9. }  

So let’s go on the top and import the map reference statement.

  1. import { map } from 'rxjs/operators'

Now let’s go into the browser and let’s go to the login page. And enter the correct credentials and sign in. Here you’ll see the validation message. Don’t worry about this validation message.

Authentication And Authorization In Angular 

As you can see it is the response object containing token. But here we want to just show this object into json. So,

  1. login(credentials) {   
  2.  return this.http.post('/api/authenticate',   
  3.     JSON.stringify(credentials))  
  4.     .pipe(  
  5.       map(respose => {  
  6.         console.log(respose['_body']);  
  7.       })  
  8.     );  
  9. }  

Now let’s take the results,

Authentication And Authorization In Angular 

So this is how it works. Now if we input the invalid username password.

Authentication And Authorization In Angular 

Now let’s store the response token in the variable and if it is true or contains the value in the token property, we’ll store it into the localStorage.

  1. login(credentials) {   
  2.  return this.http.post('/api/authenticate',   
  3.     JSON.stringify(credentials))  
  4.     .pipe(  
  5.       map(respose => {  
  6.         let result = respose['_body'];  
  7.         if (result && result.token) {  
  8.           // We wanna store it in localStorage  
  9.           localStorage.setItem('token', result.token);  
  10.           return true;  
  11.         }  
  12.    return false;  
  13.       })  
  14.     );  
  15. }  

So we are mapping the response object to boolean. Otherwise if it is not the valid login we return false.

Now let’s test the application. On valid login, we’re redirected to the Home page and that seems to be working. Now open the chrome developer tools and go to the Application tab and then Local Storage.

Authentication And Authorization In Angular 

So let’s recap, when the user logins. It sends the post request to an api endpoint to validate the credentials. If the credentials are valid we should get the json web token and store it in the localStorage. And then it is better to return boolean instead of Response object. So this is how we implement login.

Implementing Logout

Implementing the logout is very easy. So let’s go to our home.component.html and here we have logout link

  1. <ul>  
  2.   <li><a routerLink="/admin">Admin</a></li>  
  3.   <li><a routerLink="/login">Login</a></li>  
  4.   <li><a>Logout</a></li>  
  5. </ul>  

And here we want to call the logout method of authService. So first we need to go to our home component.

  1. export class HomeComponent {  
  2.   constructor(private authService: AuthService) { }  
  3. }  

And here we have already injected the authService in the constructor. So now we can bind the link with authService.logout()

  1. <li><a (click)="authService.logout()">Logout</a></li> 

Now let’s implement this method. So authService, here we have logout(). All we have to do here is to delete the token here because of the existence of the valid token inside localStorage which means we have a loggedIn user otherwise if there is no token there that means this user is logged out. So,

  1. logout() {   
  2.   localStorage.removeItem('token');  
  3. }  

Now open the browser,

Authentication And Authorization In Angular 

Showing or Hiding Elements

So we have implemented the login and logout. But when we logged in, we should not see this Login link once again.

Authentication And Authorization In Angular 

And also when we logout, we should not see the Admin and Logout links. So let’s see how to implement this. Here in authService, we have the method isLoggedIn() which is currently returning false.

  1. isLoggedIn() {   
  2.   return false;  
  3. }  

Now instead we want to get our token decoded, get its expression date and if it is not expired that means user is logged in. So in other words, if we have the token a valid token in localStorage and this token is not expired that means the user is logged in and here we should return true, otherwise we should return false.

As we have discussed earlier, in order to work with json web token we’ll use the library jwt.io. So in Angular applications, we need to install the library called Angualr2-jwt. And we have already installed this package.

Now back here again in auth.service.ts, and here we use JwtHelper

Auto import adds this import statement automatically.

  1. import { JwtHelper } from 'angular2-jwt'

And here is the function code.

  1. isLoggedIn() {   
  2.   let jwtHelper = new JwtHelper();  
  3.   return false;  
  4. }  

jwtHelper has a bunch of useful methods. Let’s use these methods here.

  1. jwtHelper.getTokenExpirationDate(); 

This method expects the token as argument. So,

  1. isLoggedIn() {   
  2.   let jwtHelper = new JwtHelper();  
  3.   let token = localStorage.getItem('token');  
  4.   let expirationDate = jwtHelper.getTokenExpirationDate(token);  
  5.   let isExpired = jwtHelper.isTokenExpired(token);  
  6.   
  7.   // Now let's log the above values on the console.  
  8.   console.log("Expiration", expirationDate);  
  9.   console.log("isExpired", isExpired);  
  10.     
  11.   return false;  
  12. }  

Now we’re going to use this method and the template for our home component. So here in home.component.html I want to render the links dynamically.

  1. <ul>  
  2.   <li><a routerLink="/admin">Admin</a></li>  
  3.   <li><a routerLink="/login">Login</a></li>  
  4.   <li><a (click)="authService.logout()">Logout</a></li>  
  5. </ul>  

So let’s make the links dynamic,

  1. <li *ngIf="authService.isLoggedIn()"><a routerLink="/admin">Admin</a></li> 

Let’s test this back in the browser. And here Admin Link vanishes before sign in and after sign in successfully. So, let’s modify some code.

  1. isLoggedIn() {   
  2.   let jwtHelper = new JwtHelper();  
  3.   let token = localStorage.getItem('token');  
  4.   
  5.   if(!token)  
  6.     return false;  
  7.   
  8.   let expirationDate = jwtHelper.getTokenExpirationDate(token);  
  9.   let isExpired = jwtHelper.isTokenExpired(token);  
  10.   
  11.   // Now let's log the above values on the console.  
  12.   console.log("Expiration", expirationDate);  
  13.   console.log("isExpired", isExpired);  
  14.   
  15.   return !isExpired;  
  16. }  

Now let’s take a look in the browser,

Authentication And Authorization In Angular 

Look in the beginning, Admin link is not visible because we have not any token. And after login we have a token in the localStorage and it's showing Admin link. And look in the console --  this token doesn’t have Expiration date.

  • Expiration null
  • isExpired false

But when you generate tokens on the server using one of the libraries provided by jwt.io, you can set the expiration date on your tokens. So back in authService, remove the console logs statements. So this is the implementation of isLoggedIn()

  1. isLoggedIn() {   
  2.   let jwtHelper = new JwtHelper();  
  3.   let token = localStorage.getItem('token');  
  4.   
  5.   if(!token)  
  6.     return false;  
  7.   
  8.   let expirationDate = jwtHelper.getTokenExpirationDate(token);  
  9.   let isExpired = jwtHelper.isTokenExpired(token);  
  10.   
  11.   return !isExpired;  
  12. }  

But there is also an easier way to implement this method. Instead of writing all this code, we can use one of the global helper functions provided by angular2-jwt. So the function is,

  1. tokenNotExpired(); 

This function does exactly what we have done above in the code. So here we can simply return tokenNotExpired().

  1. isLoggedIn() {   
  2.   return tokenNotExpired();  
  3. }  

So if the token is not expired, the user is loggedIn. Now you have a better understanding of what is happening under the hood.

Now come back to the home.component.html and complete the task.

  1. <ul>  
  2.   <li *ngIf="authService.isLoggedIn()"><a routerLink="/admin">Admin</a></li>  
  3.   <li *ngIf="!authService.isLoggedIn()"><a routerLink="/login">Login</a></li>  
  4.   <li *ngIf="authService.isLoggedIn()"><a (click)="authService.logout()">Logout</a></li>  
  5. </ul>  

And here is the result of what we have done.

Authentication And Authorization In Angular 

Showing and Hiding Elements Based on Users Role

So let’s explore something more and take our application to the next level. So what if we want to display this Admin link only to the users who are in the Admin Role. Let’s get started.

Authentication And Authorization In Angular 

So this is the content of our json web token. In the payload we have 3 properties UserId, Name, Admin. So on the server when the user authenticates, if the user is in Admin Role we can set this property to true. Another implementation would be include all the roles the user is part of. So here instead of the Admin property, we have another property called Roles which will be an array. And in this array, user can list all the Roles user can be part of. So the server generates this token, now on the client we need to decode this token to access the payload properties and then paste on these properties we can show or hide various elements on the page. So let’s see how can we do this.

Back in authService, we define another property

  1. get currentUser() {  
  2.   let token = localStorage.getItem('token');  
  3.   if(!token) return null;  
  4.   
  5.   let jwtHelper = new JwtHelper();  
  6.   return jwtHelper.decodeToken(token);  
  7. }  

And we can make this code a little bit shorter. So,

  1. get currentUser() {  
  2.   let token = localStorage.getItem('token');  
  3.   if(!token) return null;  
  4.   
  5.   return new JwtHelper().decodeToken(token);  
  6. }  

So back in home.component.html, here is our admin link

  1. <li *ngIf="authService.isLoggedIn()"><a routerLink="/admin">Admin</a></li> 

We want to render this only if the user is logged in and he’s in the admin user

  1. <li *ngIf="authService.isLoggedIn() && authService.currentUser.admin">  
  2.   <a routerLink="/admin">Admin</a>  
  3. </li>  

Now back in the browser.

Authentication And Authorization In Angular 

So because I’m an admin user that’s why Admin link is showing to me. But let’s log out and generate a new token that doesn’t have admin property. So back to jwt.io and change the admin to false,

Authentication And Authorization In Angular 

Now copy the token and we're going to use this and hard code this token in our fakeBackend. So copy the token and go to the fakeBackend and replace the token.

let token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlVzYW1hIFNoYWhpZCIsImFkbWluIjpmYWxzZX0.14FzmpTgliDscuwsfJAebGqXwVS8rye_EE0URrCohTk';

Now test the application.

Authentication And Authorization In Angular 

So this user is not the admin. So admin link is not showing to us. As we already discussed this token has a digital signature that is generated based on the content of the token and a secret. So if the malicious user goes into the application tab and gets the token

Authentication And Authorization In Angular 

And then decodes it here in jwt.io and decodes the token and accesses the payload and header content. But he can’t change the content of any property in payload or in header. Because in order to generate the signature, we need to have the secret and the secret is not on the client

Authentication And Authorization In Angular 

Secret is only on the server.

Come again in the fakeBackend and revert changes and use the old token that has the admin access. So this is how we can check to see if the user is the part of the given roles.

Getting the Current User

Now let’s display the name of the current user. So open the home.component.html and here we use string interpolation with our currentUser property.

  1. <p>  
  2.   Welcome {{ authService.currentUser.name }}  
  3. </p>  

And of course we want to render this only if the user is logged in. So,

  1. <p *ngIf="authService.isLoggedIn()">  
  2.   Welcome {{ authService.currentUser.name }}  
  3. </p>  

Now let’s test the application.

Authentication And Authorization In Angular 

And if we Logout, the welcome message disappears.

CanActivate Interface

Let’s see a vulnerability in our application. Currently I’m logged out and I don’t see the Admin link. However if I go to the browser address bar and access the admin page, it is accessible.

Authentication And Authorization In Angular 

So how can we solve this issue? In Angular, we have the concept called Route Guard that we can apply to various routes to protect them. Let’s see how that works. Back in the terminal and here we generate a new service.

PS C:\Users\Ami Jan\auth-demo\auth-demo> ng g s services/auth-guard

Here services is the name of the folder where scaffolded service is placed. And auth-guard is the name of the service. Now let’s go to the new service. Here we use the naming convention of AuthGuard instead of AuthGuardService and here we activate the CanActivate interface. So let’s go to the angular.io and search for CanActivate and here you can see the shape of CanActivate interface. So we need to add a method in our class called canActivate which takes 2 parameters route which is of ActivatedRouteSnapshot and state which is of type RouterStateSnapshot but now we’ll exclude these parameters and simplify things but in the next we’ll see where we use these parameters.

  1. import { Injectable } from '@angular/core';  
  2. import { CanActivate } from '@angular/router';  
  3.   
  4. @Injectable()  
  5. export class AuthGuard implements CanActivate {  
  6.   
  7.   constructor() { }  
  8.   
  9.   canActivate() {  
  10.       
  11.   }  
  12. }  

Now in this canActivate() we need to check to see if the user is logged in or not. If he’s logged in, we’ll return true otherwise we should navigate the user to log in page and return false. So in order to check to see if the user is log in or not, we need to inject authService into the constructor of this class. And then in canActivate() we can check,

  1. export class AuthGuard implements CanActivate {  
  2.   
  3.   constructor(private authservice: AuthService) { }  
  4.   
  5.   canActivate() {  
  6.     if(this.authservice.isLoggedIn()) return true;  
  7.   }  
  8. }  

And if the user is not logged in we’ll navigate to the home page. So here we need to inject the router service into the constructor of this class.

  1. export class AuthGuard implements CanActivate {  
  2.   
  3.   constructor(  
  4.     private router: Router,  
  5.     private authservice: AuthService) { }  
  6.   
  7.   canActivate() {  
  8.     if(this.authservice.isLoggedIn()) return true;  
  9.   
  10.     this.router.navigate(['/login']);  
  11.     return false;  
  12.   }  
  13. }  

So this is what we called Route Guard. Now we need to apply this guard on admin route. So let’s go to the app.module.ts

  1. RouterModule.forRoot([  
  2.   { path: '', component: HomeComponent },  
  3.   {   
  4.     path: 'admin',   
  5.     component: AdminComponent,  
  6.     canActivate: [AuthGuard]  
  7.   },  
  8.   { path: 'login', component: LoginComponent },  
  9.   { path: 'no-access', component: NoAccessComponent }  
  10. ])  

canActivate has an array containing the RouteGuard classes. So with the help of this technique, we can use reuse this Auth Guard and apply it on any routes that should be protected from the anonymous user. Now let’s test the application; back in the browser if we request the url localhost:4200/admin. It navigates to the home page localhost:4200 but here we’re watching a white screen, it means here is some error in the console.

Authentication And Authorization In Angular 

So the error first line is Error: No Provider for AuthGuard! So before registering AuthGuard as a provider for dependency injection, back in app.module.ts, in the providers array we’ll add AuthGuard here as well.

  1. providers: [  
  2.   OrderService,  
  3.   
  4.   AuthService,  
  5.   AuthGuard,  
  6.   
  7.   // For creating a mock back-end. You don't need these in a real app.   
  8.   fakeBackendProvider,  
  9.   MockBackend,  
  10.   BaseRequestOptions  
  11. ]  

Now back in the browser,

Authentication And Authorization In Angular 

So in Angular, we use RouteGuard to protect the routes from anonymous users.

Redirecting Users After Logging In

Now let’s suppose I’m the admin user. So when I logged out in the application, and request for the admin page I navigate to the login page. But after successfully signing in, it should go to the url which was requested and we navigated to the login page. So when we navigate to the login page, we should also have the query parameter like returnUrl

http://localhost:4200/login?returnUrl=xyz

So back in our AuthGuard where we navigate the user to login page, here we’ll pass the 2nd argument to the navigate method. And this 2nd argument is an object with 1 property and this property is also an object containing returnUrl property.

  1. this.router.navigate(['/login'], { queryParams: { returnUrl: }}); 

Now what should we use here? We have already seen the documentation of CanActivate interface. And we know that CanActivate interface takes 2 parameters, route and state. Now with this state parameter we can get access to the url that the user wanted to access. So,

  1. canActivate(route, state: RouterStateSnapshot) {  
  2.   if(this.authservice.isLoggedIn()) return true;  
  3.   
  4.   this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});  
  5.   return false;  
  6. }  

This is all we have to do to send this query parameter to the login page. Here we can also optionally annotate route parameter but it doesn’t add any value. Now we should go to our login component and get this query parameter. So open login.component.ts, in order to access route parameters we need to inject ActivatedRoute service into the constructor of this class. And in the signIn(), when the user successfully logs in, instead of navigating it to the home page we should check the query parameters and if it has returnUrl we want to send the user then we’ll use returnUrl for navigation otherwise return them to the home page.

  1. export class LoginComponent {  
  2.   invalidLogin: boolean;   
  3.   
  4.   constructor(  
  5.     private router: Router,   
  6.     private route: ActivatedRoute,  
  7.     private authService: AuthService) { }  
  8.   
  9.   signIn(credentials) {  
  10.     this.authService.login(credentials)  
  11.       .subscribe(result => {   
  12.         if (result) {  
  13.           let returnUrl = this.route.snapshot.queryParamMap.get('returnUrl');  
  14.           this.router.navigate([returnUrl || '/']);  
  15.         }  
  16.         else    
  17.           this.invalidLogin = true;   
  18.       });  
  19.   }  
  20. }  

So if the user has returnUrl, it will navigate to the returnUrl otherwise to the home page. Now let’s test it in the browser.

Authentication And Authorization In Angular 

Protecting Routes Based on User Role

Now let’s take this application to the next level, I want to make this admin route accessible only to users with the admin role. Currently anyone who is logged in can access the admin page.

Authentication And Authorization In Angular 

So let’s see how to fix this problem. Earlier in app.module.ts, we have applied this AuthGuard in our admin route.

  1. {   
  2.   path: 'admin',   
  3.   component: AdminComponent,  
  4.   canActivate: [AuthGuard]  
  5. }  

Here we saw, we have an array. And in this array we can have multiple guards. And these guards are applied in sequence. So first we want to our AuthGuard to be applied. Now we gonna implement another guard which ensures that only admin users can access this route. So come back to the terminal and generate one more service.

PS C:\Users\Ami Jan\auth-demo\auth-demo> ng g s services/admin-auth-guard

Now open adminauthguard class. And here once again rename the class name and implement CanActivate interface as well

  1. import { Router } from '@angular/router';  
  2. import { CanActivate } from '@angular/router';  
  3. import { Injectable } from '@angular/core';  
  4. import { AuthService } from './auth.service';  
  5.   
  6. @Injectable()  
  7. export class AdminAuthGuard implements CanActivate {  
  8.   
  9.   constructor(  
  10.     private router: Router,  
  11.     private authService: AuthService  
  12.   ) { }  
  13.   
  14.   canActivate() {  
  15.       
  16.   }  
  17. }  

Now in canActivate() first we need to check to see if the user is an admin or not. So,

  1. canActivate() {  
  2.   this.authService.currentUser.admin      
  3. }  

In the last dot, we don’t get the intellisense because we haven’t annotated this property. So potentially in the future we can define an interface, applied on this property and then we’ll get compile time checking as well as intellisense. Now come back again to the point,

  1. canActivate() {  
  2.   if(this.authService.currentUser.admin) return true;  
  3.   
  4.   // Navigate to the Permission Denied Page  
  5.   this.router.navigate(['/no-access']);  
  6.   return false;  
  7. }  

Now let’s go back to our app.module.ts and apply this new guard as well.

  1. {   
  2.   path: 'admin',   
  3.   component: AdminComponent,  
  4.   canActivate: [AuthGuard, AdminAuthGuard]  
  5. }  

And providers array is,

  1. providers: [  
  2.   OrderService,  
  3.   
  4.   AuthService,  
  5.   AuthGuard,  
  6.   AdminAuthGuard,  
  7.   
  8.   // For creating a mock back-end. You don't need these in a real app.   
  9.   fakeBackendProvider,  
  10.   MockBackend,  
  11.   BaseRequestOptions  
  12. ]  

Now one tiny problem in the code is, here we’re expecting that currentUser.admin always has a value but as you know currentUser will be null if the user is not logged in. This is actually not the issue because we have applied AdminAuthGuard after AuthGuard. So this code, currentUser.admin is executed only if the user is logged in which means current user will have a value. But to make it little bit more robust, it is better to change the if statement and ensure that current user is not logged. So,

  1. canActivate() {  
  2.   let user = this.authService.currentUser;  
  3.   if(user && user.admin) return true;  
  4.   
  5.   // Navigate to the Permission Denied Page  
  6.   this.router.navigate(['/no-access']);  
  7.   return false;  
  8. }  

Now it looks more clean as well. Now let’s test the result in the browser.

Authentication And Authorization In Angular 

Accessing Protected API Resources

So far our focus has been purely on showing/hiding parts of the page and also on protecting the routes. But when it comes to implementing authentication and authorization in real world applications, we should also know how to access protected api resources. For example, here we have admin page containing list of orders and this list is supposed to come from our api endpoint. As you imagine, this api endpoint is only be accessible to logged in users who are in admin role.

Authentication And Authorization In Angular 

And currently on this admin page, we don’t see the list of orders. And here we’ll see how to fix this problem. So here we have the api/orders endpoint fake implementation,

  1. if (connection.request.url.endsWith('/api/orders') &&   
  2.     connection.request.method === RequestMethod.Get) {  
  3.   if (connection.request.headers.get('Authorization') === 'Bearer ' + token) {  
  4.      connection.mockRespond(new Response(  
  5.        new ResponseOptions({ status: 200, body: [1, 2, 3] })  
  6.   ));  
  7. else {  
  8.     connection.mockRespond(new Response(  
  9.       new ResponseOptions({ status: 401 })  
  10.     ));  
  11. }  

So look at the logic here, we look at the request headers and if we have a header with this name Authorization and the value of the header is this specific and on condition true we send the response with status 200 and in the body of the request we're going to include orders. As we already discussed, we should implement this logic at our api endpoint on the server. So we need to check the existence of Authorization header and its value and the token should not be expired then you would grant access to api resources. Once again, you don’t need to write all these code instead you can use one of the provider libraries on jwt.io for your platform.

Come back to the point and focus on the front end. Open the order.service.ts and here we have a method getOrders() sending get request to our orders endpoint. The reason we don’t get the list of orders is because we don’t have included the authorization header. So let’s see how we can add authorization header to this request.

  1. getOrders() {   
  2.   return this.http.get('/api/orders')  
  3.     .map(response => response.json());  
  4. }  

Here first we need to create headers object and this instance has a method called append. And here we need to pass name and the value

  1. getOrders() {   
  2.   let headers = new Headers();  
  3.   let token = localStorage.getItem('token');  
  4.   headers.append('Authorization''Bearer' + token);  
  5.   
  6.   return this.http.get('/api/orders')  
  7.     .map(response => response.json());  
  8. }  

Next we need to create RequestOptions object and on initialization we pass the object and in this object we set the headers property to the headers object we created.

  1. let options = new RequestOptions({ headers: headers });  

Here we have compilation error because type mismatches. The reason for this is because this headers type (new Headers()) is defined natively in the browser but we wanna use headers type defined in Angular. So we need to explicitly import Headers type of Angular.

  1. import { Http, RequestOptions, Headers } from '@angular/http';  

And function is,

  1. getOrders() {   
  2.   let headers = new Headers();  
  3.   let token = localStorage.getItem('token');  
  4.   headers.append('Authorization''Bearer' + token);  
  5.   
  6.   let options = new RequestOptions({ headers: headers });  
  7.   
  8.   return this.http.get('/api/orders')  
  9.     .map(response => response.json());  
  10. }  

And now the compilation error is gone. Now we pass this options object to the 2nd argument of the get() method.

  1. return this.http.get('/api/orders', options)  
  2.   .map(response => response.json());  

Now let’s test the application,

Authentication And Authorization In Angular

We can see we have 3 orders. So when building APIs on the server, if we want to secure web apis endpoints we should ensure that the real ‘Authorization’ header  is in the request. And the value of this header should be a valid json token. And this means on the client in your Angular apps whenever you need to access protected api endpoints, we should always supply this ‘Authorization’ header

  1. let headers = new Headers();  
  2. let token = localStorage.getItem('token');  
  3. headers.append('Authorization''Bearer' + token);  
  4. let options = new RequestOptions({ headers: headers });  

But as you can see, writing all this code in multiple places is repetitive and time consuming. So let’s see the faster way, in Angular2-jwt we have AuthHttp class. And with the help of AuthHttp instance object we can request the same http endpoints implementing the same logic (get the token from localStorage and add this token in Authorization key in Header and then assign this header in the RequestOptions). So the new implementation is,

  1. import { map } from 'rxjs/operators';  
  2. import { Http, RequestOptions, Headers } from '@angular/http';  
  3. import { Injectable } from '@angular/core';  
  4. import 'rxjs/add/operator/map';  
  5. import { AuthHttp } from 'angular2-jwt';  
  6.   
  7. @Injectable()  
  8. export class OrderService {  
  9.   
  10.   constructor(private authHttp: AuthHttp) {  
  11.   
  12.   }  
  13.   
  14.   getOrders() {  
  15.     return this.authHttp.get('/api/orders')  
  16.       .map(response => response.json());  
  17.   }  
  18. }  

And if you want to use standard Http class to request the api endpoints then we can add one more dependency in the constructor as well and we can use it in other methods for our ease.

  1. constructor(  
  2.   private authHttp: AuthHttp,  
  3.   private http: Http  
  4. ) {  

When we’re working with AuthHttp we also need to define it in the app.module.ts as well. So here is our providers array in app.module.ts

  1. providers: [  
  2.   OrderService,  
  3.   
  4.   AuthService,  
  5.   AuthGuard,  
  6.   AdminAuthGuard,  
  7.   AuthHttp,  
  8.   
  9.   // For creating a mock back-end. You don't need these in a real app.   
  10.   fakeBackendProvider,  
  11.   MockBackend,  
  12.   BaseRequestOptions  
  13. ]  

Conclusion

Let’s quickly recap the important points of this lesson. So we learned Json Web Tokens (JWT) to implement Authentication and Authorization in our Angular apps. These json web tokens have a header, a payload and a digital signature that is based on the combination of header and payload and is generated based on a secret. This secret is known only on the server. We also looked at jwt.io where we have json web token debugger as well as libraries we can use both on the clients and on the server. And in angular apps, we use npm package angular2-jwt as for as Authorization.

There are 2 things on the client that you need to look for, you need to show/hide elements on the page depending on the authentication status of the user whether they’re logged in or not or maybe they are logged in but part of the specific role. And here we use ng directive to show and hide parts of the page. And we should never ever ever have sensitive information on the client. Because a malicious user can obviously look in the DOM look for the things that you have hidden. So when we hide certain elements on the page, we’re talking about the content that is not sensitive like links to an Admin page. And the second thing is, we should protect our routes. And we use guards to achieve that. So these are things we should keep in mind on the client.

And on the server, we want to protect all api endpoints where the subset of the api endpoints from unauthorized access. And once again to do that, we use json web tokens. So on these api endpoints, we should expect an authorization header with the valid json web token in the request.