Authentication in Angular, why it is so hard to wrap your head around it
The basic ingredients
Series:
Angular Auth
By definition of an SPA: single page application, all elements on the screen are no longer part of a global page state, but have their own existence, and lifespan. Authentication, and authorization., affect some or all of the elements on the screen, making it the odd one out.
Authentication ingredients
A full cycle of authentication and authorization in an SPA may go through the following factors:
User login: getting an access token, and possibly a refresh token.
Storing on client: in local storage along with minimal details
Login resolver: to direct away from the login page if the user is already authenticated
Router auth guard: to direct to login page if user is not authenticated
Logout: remove storage
Use cases:
Http interceptor: to use the token for API calls
401 handling: to request a new token
User display: getting extra details to display on the screen
Redirect URL: an extra piece of information to track
Other concerns:
Third-party: how much do we need to change to adapt
Server-side rendering: getting the access token by other means
We should always remind ourselves as we build authentication that:
Not all routes go through an auth guard
Some components display user status anyway
There is a sequence of events taking place in an Angular app
Follow along on StackBlitz
The simplest login
Let us begin with the simplest format of authentication, a form with user name and password, that returns a profile with an access token, and possibly a refresh token. Over the years, I have come to terms with a few things and tend to never argue about them:
Yes sign the token on the server and return both access token and refresh token to the client
Yes, save them both in
LocalStorage
Yes, extract and save everything you need on the client
No, you don’t have to have a server for the front end
The API is a simple POST that accepts username and password and returns a dummy access token and a refresh token. First, let’s get one thing out of the way. A login button.