đAuth0 in Angular : [Part1]Authenticate your Angular app
This is part 1 of the âAuth0 in Angularâ beginners series. In this series we will learn how to secure an Angular application using Auth0. This article covers the user authentication with Auth0.
You wonât become an Auth0 pro after reading this series, but youâll have a good foundation that will help you start using Auth0 in your everyday Angular development.
Step 1 : Configure an Auth0 application
After setting up an account in Auth0, head over to the Applications section on the left menu, click on the Applications sub-menu. Then, click on the âCreate Applicationâ button and make sure to choose the Single page web applications option and click on create. I named the application âMy Appâ.
Now that everything is setup correctly, go to the settings tab, you will find :
- Basic information including the domain, client Id, client Secret etc. We will need the Domain and Client ID properties later to configure our Angular app.
- Application properties including the application type, logo, URIs etc
- Tokens properties such as refresh token, ID token etc
- Advanced properties such as Grant Types, Certificates, Ws-Federation etc
We will need to set the Callback URLs , Logout URLs and Allowed Web origins properties (available in the âSettingsâ tab under âApplication URIsâ section) to http://localhost:4200
which is the URL of our Angular app and save the changes as follows:
Step 2 : Create a User
You have to create a user for your application by going to the menu Users under User Management and hit the button âCreate Userâ. A popup will show up, you have to fill your user details and submit.
Now that we have configured our Auth0 app and create the user letâs move to the Angular part configuration.
Step 3 : Install and register the Auth0 Angular SDK
Open your Angular application and install auth0-angular which is a library that helps though providing many utilities integrating Auth0 into an Angular 9+ applications.
ng add @auth0/auth0-angular
Now letâs register and configure the authentication module in our Angular app as follows :
- Open the
app.module.ts
file - Import the
AuthModule
type from the@auth0/auth0-angular
package that contains all the services required for the SDK to work properly. - Add
AuthModule
to your imports by callingAuthModule.forRoot
and pass as a parameter the propertiesdomain
andclientId
The values of the properties domain
and clientId
should match respectively the value of the âDomainâ and âClient IDâ properties available under the âSettingsâ tab, section âBasic Informationâ of the Auth0 application we registered in the Step 1.
For more details about the forRoot pattern please head to https://angular.io/guide/singleton-services#the-forroot-pattern
Step 4: Add Login to your Application
The Auth0 SDK provides useful apis to quickly implement authentication in your Angular apps, such as the loginWithRedirect()
method from the AuthService
service class that :
- Redirects your users to the Auth0 Universal Login Page, where Auth0 can authenticate them.
- Redirects your users back to your application when the authentication is successful
In order to use this method, you should inject the AuthService
in your login component and call the method loginWithRedirect()
when logging in
Then, you should call the login() method when clicking on the âLog inâ button in your LoginComponent template file as follows :
This way when you click on the âLog inâ button you will get redirected to the Auth0 Universal Login Page and if the authentication is successful you will get redirected back to your app.
You can checkout your authentication state by going to the application cookies, the values of the authentication cookies will be true as follows :
So far so good ! But with this example the âLog inâ button will always be visible even if the authentication is successful. To resolve this we can use the exposed observable isAuthenticated$
from the AuthService
to check the authentication state and only display the âLog inâ button when the value is false as follows :
The async pipe subscribes automatically to the input Observable (isAuthenticated$
in our case) when the component is created and unsubscribes automatically when the component is destroyed. Besides, it always returns the last value emitted by the input Observable.
Step 5: Add Logout to your Application
Now for the logout part, itâs the exact same thing as the login except the method to call. This time we will use the logout()
method from the AuthService
in our LogoutComponent as follows :
Letâs break down what is happening at the level of this code. We injected the AuthService
in our LogoutComponent and implemented a logout() method that calls the method logout()
from the AuthService
. This method takes as input an optional configuration object of type LogoutOptions
. We will use the property âreturnToâ from this object to customize the logout redirect URL. In our case we will redirect to the original location available in the âdocumentâ. In order to have access to the âdocumentâ we injected the document constant available in the @angular/common package as a dependency.
Now in the LogoutComponent template file we should call the logout() method after clicking on the âLog outâbutton. The button should only be visible when the user is authenticated.
Now if we look into the browserâs network after performing the logout we will see two ongoing requests. In fact, executing logout() redirects your users to your Auth0 logout endpoint (https://YOUR_DOMAIN/v2/logout) and then immediately redirects them to your application.
And Thatâs it !
Thanks for reading đ
In the next article we will explore the user preferences and roles management using Auth0.