Search⌘ K
AI Features

Auth Service

Understand how to build an Angular Auth Service to manage user login status with angular-jwt. Learn to create route guards that protect views by redirecting unauthenticated users, and write tests for authentication logic using unit testing.

We left off the last chapter with an issue related to our user dashboard. Our dashboard should only be viewable to users who are logged in. If they aren’t, they should be redirected to another view, such as /signup or /login instead.

To do this, we’ll create a route guard within Angular.

AuthGuard setup

First, we’ll create a guard within a new directory for our route guards.

ng g guard guards/auth/auth
Terminal 1
Terminal
Loading...

When running this command, there may be a prompt asking which type of interface we’d like to implement for the route guard. Select CanActivate if it isn’t already selected by default and hit enter.

In addition to creating the route guard, the CLI has created two new directories, src/app/guards and src/app/guards/auth, along with two files. This should be the terminal output:

CREATE src/app/guards/auth/auth.guard.spec.ts
CREATE src/app/guards/auth/auth.guard.ts

Authenticate - isLoggedIn

Before we get to the guard itself, we must ask ourselves, what ...