Installation
The Angular SDK is compatible with Angular SPAs version 14 and above.
ng add @auth0/auth0-angular
Getting started
Begin integrating the SDK by importingAuthModule into your project and configuring it for your Auth0 client app:
Login
The SDK fully supports Angular’s dependency injection system. To begin, import theAuthService type into a component and inject it into the constructor.
Then, to initiate user login, call the loginWithRedirect or loginWithPopup methods on the service:
Logout
Uselogout to log your users out. Make sure returnTo is specified in Allowed Logout URLs in your .
Authentication State
The authentication state is exposed through theisAuthenticated$ observable:
User Profile
The user profile for the authenticated user is exposed through theuser$ observable:
isAuthenticated$ observable, so there is no need to manually check if the user is logged in. It will begin emitting values once an authenticated user is available.
Protect a route
Protect a route component using the built-inAuthGuard. Visits to this route when unauthenticated will redirect the user to the login page and back to this page after login.
The authentication guard should be added to a route definition using the canActivate hook (or canActivateChild if using child routes):
canLoad hook for preventing lazy-loaded modules from being loaded when the user is unauthenticated.
Call an API
The SDK contains a built-inHttpInterceptor that automatically attaches by injecting an Authorization header when requests are made using Angular’s HttpClient service.
You must configure the SDK to specify which routes to the API should have this header automatically added, to prevent access token leakage to recipients that you did not expect.
Import the HTTP interceptor
To start, import the types that you will need in order to integrate the Auth0 HTTP interceptor into your app:Configure the HTTP interceptor
There are a variety of ways to configure this depending on your needs. A route can be specified using a string, an object with options that influence the token being sent, and can also be matched depending on the HTTP verb being used. Route URIs can also include a wildcard to specify a group of routes. Note: If an HTTP call is made but does not match a route specified in the configuration, the interceptor will be bypassed and theAuthorization header will not be included.
This example shows common ways to tell the SDK which routes should have an Authorization header:
tokenOptions is passed directly to the getTokenSilently method on the underlying SPA SDK. Please see the documentation for more detail on the properties that are accepted.
Call an API
Make your API call using Angular’sHttpClient service. Access tokens should automatically be included via the Authorization header for routes that match the configuration.