Chapter 12. Using an authentication API in Angular applications


This chapter covers

  • Using local storage and Angular to manage a user session
  • Managing user sessions in Angular
  • Using JWT in Angular Applications

In this chapter, you’ll integrate the work that you completed in chapter 11 on authentication via API and use the API endpoints in your Angular application. Specifically, you’ll look at how to use the Angular HTTP client library and localStorage.

12.1. Creating an Angular authentication service

In an Angular app, as in any other application, authentication is likely to be needed across the board. The obvious thing to do is create an authentication service that can be used anywhere it’s needed. This service should be responsible for everything related to authentication, including saving and reading a JWT, returning information about the current user, and calling the login and register API endpoints.

You’ll start by looking at how to manage the user session.

12.1.1. Managing a user session in Angular

Assume for a moment that a user has just logged in and the API has returned a JWT. What should you do with the token? Because you’re running an SPA, you could keep it in the browser’s memory. This approach is okay unless the user decides to refresh the page, which reloads the application, losing everything in memory—not ideal.

12.2. Creating the Register and Login pages

12.3. Working with authentication in the Angular app