Protect App

At this stage, authenticating does not affect what users are able to see and access in our todo app. They can interact with the todo list regardless of whether or not they're logged in. Let's take one more step to protect our todo list with our new authentication layer.

If we want to only let authenticated users see and interact with the todo list, we can implement this easily!

Provide AuthService in List Manager

Open the list-manager.component.ts file. The first thing we'll do is import the AuthService and then we'll pass it to the constructor function. We want to use AuthService methods in the template, so we'll need to pass the argument as public:

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

...

constructor(public authService: AuthService) { ...

Only Load Todo if Authenticated

Now we can use NgIf to only render our todo list if the user is authenticated. Update the component's inline template to the following:

...

  template: `
    <div class="todo-app">
      <h1>
        {{title}}
      </h1>

      <p *ngIf="!authService.isLoggedIn">
        You must log in to access the todo app!
      </p>

      <ng-template [ngIf]="authService.isLoggedIn">
        <div class="todo-add">
          <todo-input (submit)="addItem($event)"></todo-input>
        </div>
        <ul>
          <li *ngFor="let item of todoList">
            <todo-item
              [todoItem]="item"
              (remove)="removeItem($event)"></todo-item>
          </li>
        </ul>
      </ng-template>
    </div>
  `,

...

If the user is not authenticated, we'll show a paragraph that tells them they must log in to access the app. If the user is authenticated, we'll display the todo list.

That's it! Test it out in the browser. If the user is not logged in, they should see something like this:

We have now protected our app with authentication!

Note: It's important to note that because our todo app uses local storage instead of an API, no additional security has been conferred to the CRUD actions in the application. In the future, if you update the app to use an API, it's important to secure the API and require a valid access token to access it.

results matching ""

    No results matching ""