(616) 371-1037

[email protected]

Securing Angular Applications

March 20, 2018 - Vitalii Chmovzh

No Comments

Single Page Applications or SPA have become the gold standard for modern web applications. Almost every application contains two major areas: secured and unsecured. Today we will learn how to restrict access to the secured area for non-authorized users in modern Angular (version 2 and higher).

No previous Angular experience is required to complete this tutorial. Chrome browser is recommended. You will be able to download complete source code at the end.


  1. NodeJS. You can download latest Node from https://nodejs.org/en/download/
  2. Angular CLI. Once you have installed Node, open the terminal and run 

    If you are getting access errors on Mac run the same script with sudo. 


Let’s start by creating a new project. Open the terminal and navigate to the place where you want to create your project. Run the following command to generate a basic Angular app:

Your app will be generated in the secure-angular-client-side folder. Navigate to it and run your app:

ng serve will start a simple development server on localhost:4200. It will also watch for any code changes and refresh your browser automatically on each change. If you open http://localhost:4200 in your browser you should see this:

At this point you can open the project in your favorite IDE and we can move to the next part, which is generating components for our application.


We will generate 3 components for our application:

  1. Login component. This component will have a simple login form for the demonstration.
  2. Shell component. This component will be our app master page and will hold the layout, such as header / footer and content area.
  3. Dashboard component. This component will represent the application dashboard which should be accessible only by logged in users.

Angular CLI provides us with an easy way to generate components. Run the following commands in the terminal from the root folder of your project:

Your components are now created under the app folder. Let’s create a components folder under app and move the newly created components there. At the end your folder structure should look like this:

Open src/app/app.module.ts and add login, shell and dashboard components to declarations:

Now let’s setup routing for our application. We will also add basic navigation between components to verify our routes work.


Create the file app.routing.module.ts under app folder and paste in the following contents:

Go to src/app/app.module.ts and add AppRoutingModule and FormsModule to imports:

Open src/app/app.component.html and replace it’s contents with the following HTML:

app.component is a root component and it has a <router-outlet> where our top-level components will be mounted and some temporary navigation to test that routing works properly.

Now open src/app/components/shell/shell.component.html and replace it contents with:

This is our master page and it will have a header and a <router-outlet> where our child components like DashboardComponent under ShellComponent will be mounted. See src/app/app.routing.module.ts for reference:

Restart ng serve and verify that you can navigate between dashboard and login with the top menu.

Before we will move to the Authorization part, we will add styling for our login page and shell. Copy and paste the following HTML and CSS snippets into the corresponding files.



src/app/app.component.html (remove everything except router-outlet)





Now we need to simulate the login/logout process. We already have a basic login form and a header with a logout button. It’s time to add the AuthService that will be responsible for handling the authorization process and providing the current auth state.


Create a services folder under app and create auth.service.ts there. This will be our AuthService. Paste the following contents into that file:

Also add AuthService to the providers array in app.module.ts: 

In the real world authorize method would send a request to an API and parse the response. Now let’s wire up authorize() and unauthorize() methods to the Sign In button on the login screen and the Logout link in the header.

Update login.component.ts. 

Here we declared 2 fields: username and password which we will bind in the template using [(ngModel)]. Also we added a signIn() method that will call authService.authorize() and in case of success it will redirect the user to the dashboard. Now open login.component.html and add the bind fields and methods that we just created. At the end login.component.html should have the following code:

Test to see if it works. Go to http://localhost:4200/login. Enter any login and password, you can even leave them blank, press sign in and you should see our dashboard page.

Now let’s update shell.component.ts:

Here we added a logout() method that will call unauthoize() on our authentication service and after that redirect the user back to login. Tweak logout link in shell.component.ts: 

..and test that you can logout by clicking Logout on dashboard.

Now we have the complete login/logout flow with two major problems:

  1. The user can open dashboard without being logged in by typing dashboard URL in the browser.
  2. The user can open login while logged in by typing login URL in the browser.

Let’s look into how to resolve those issues in an effective way in Angular in the final chapter.


Guards are a very powerful feature implemented in the latest Angular. Guard is a class that implements one of the interfaces and returns true or false from the corresponding function. There are 5 types of route guards at the moment: CanActivate, CanActivateChild, CanDeactivate, CanLoad and Resolve. In our application we will use CanActivate guard. You can read more about other types of guards from the official Angular documentation: https://angular.io/guide/router#milestone-5-route-guards.

Let’s start by creating a guards folder under app. Then go back to the terminal and run the following commands:

You will see the newly created guards under the app folder. Move them into the guards folder.

Open auth.guard.ts. You can see that the Angular CLI generates a CanActivate guard by the default:

Currently the guard returns true, so if we put it on some route, it will allow access to the route every time. Notice that we can return an Observable or Promise from that function. This is handy when you need to make API call to decide whether the user can access specific route or not, e.g. fetching permissions from the API.

Open the app.routing.module.ts and assign guards to routes in the following way:

Note AuthGuard on ShellComponent. You don’t need to assign it to each child as well – just to the parent route. Child routes will be automatically be guarded by the parent and that’s another reason why we want to have the ShellComponent.

Update the providers array in the app.module.ts: 

As a final part let’s add some logic into AuthGuard and NonauthGuard. We need to inject AuthService and Router into both guards and check if the user is authorized in the canActivate function. Depending on that we should either return true allowing him to access the route or redirect him to some page that we know he has access to, e.g. login if user is not authorized or dashboard in the opposite case.



Now we are ready for the final test.

Clean localStorage by opening the browser console and typing localStorage.clear(). Refresh the page. You should land on the login page even if you stayed on the dashboard before. Try to access the dashboard by changing the URL: you will not be able to do this. Every time the app will redirect you back to the login page. Now login to the app and try to go to the login page. Again the app will stay on the dashboard.


This is how you can easily secure any Angular app. Note that guards can be used in different variations, not only to check auth, but also with roles, permissions, etc. You can also have multiple guards on a single route. In that case the route will be activated only if all of them return true.

You can also download the complete example of this app from Github: https://github.com/trailheadtechnology/secure-angular-client-side.git

Vitalii Chmovzh

Leave a comment

Your email address will not be published. Required fields are marked *