This tutorial demonstrates how to add user login to an Angular (versions 2 and above) application using Auth0. We recommend you to Log in to follow this quickstart with examples configured for your account.
I want to integrate with my app15 minutes
I want to explore a sample app2 minutes
Get a sample configured with your account settings or check it out on Github.
Get Your Application Keys
When you signed up for Auth0, a new application was created for you, or you could have created a new one.
You will need some details about that application to communicate with Auth0. You can get these details from the Application Settings section in the Auth0 dashboard.
You need the following information:
- Client ID
Configure Callback URLs
A callback URL is a URL in your application where Auth0 redirects the user after they have authenticated.
The callback URL for your app must be whitelisted in the Allowed Callback URLs field in your Application Settings. If this field is not set, users will be unable to log in to the application and will get an error.
Configure Logout URLs
A logout URL is a URL in your application that Auth0 can return to after the user has been logged out of the authorization server. This is specified in the
returnTo query parameter.
The logout URL for your app must be whitelisted in the Allowed Logout URLs field in your Application Settings. If this field is not set, users will be unable to log out from the application and will get an error.
Configure Allowed Web Origins
You need to whitelist the URL for your app in the Allowed Web Origins field in your Application Settings. If you don't whitelist your application URL, the application will be unable to automatically refresh the authentication tokens and your users will be logged out the next time they visit the application, or refresh the page.
Integrate Auth0 in your Application
You need the
auth0-spa-js library to integrate Auth0 into your application.
You can either install the library locally in your application or load it from CDN.
Loading via dependencies
auth0-spa-js using npm or yarn.
auth0-spa-js is installed, reference it using an import statement (if you're using a build system such as Webpack):
Loading it from CDN
If you do not want to use a package manager, you can retrieve
auth0-spa-js from Auth0's CDN.
Authentication with Auth0
Universal Login is the easiest way to set up authentication in your application. We recommend using it for the best experience, best security and the fullest array of features. This guide will use it to provide a way for your users to log in to your Angular 7+ application.
When a user logs in, Auth0 returns three items:
access_token: to learn more, see the Access Token documentation
id_token: to learn more, see the ID Token documentation
expires_in: the number of seconds before the Access Token expires
You can use these items in your application to set up and manage authentication.
This tutorial will guide you in modifying an Angular application to support login using Auth0, that demonstrates how users can log in, log out, and how to view their profile information. It will also show you how to protect routes from unauthenticated users.
Create an Angular application
If you do not already have an application in which to implement the SDK, a new one can be generated using the Angular CLI.
Install the CLI:
Then use it to generate a new Angular application. When asked "Would you like to use Angular routing?", select yes:
Once the project has been created, open the
auth0-angular-demo folder in your favorite code editor.
Finally, by default the application runs on port
4200. This should run on port
3000 so that it matches the Auth0 URLs configured above. This can be done inside the
package.json file by modifying NPM's
start command as follows:
Install the SDK
While in the project folder, install the SDK using
npm in the terminal:
Add an Authentication Service
To make it easier to use the Auth0 SDK within an Angular application, create an Angular service that can be injected into other components and services. This service can be used to set up and retrieve an instance of
To start, generate a new service called
src/app/auth.service.ts file inside your code editor and add the following content:
This service provides a single method
getAuth0Client. When called, it will in turn call
createAuth0Client from the Auth0 JS SDK and save it in a class-level variable. Subsequent calls to
getAuth0Client will return the same instance.
Note that the
redirect_uri property is configured to indicate where Auth0 should redirect to once authentication is complete. For login to work, this URL must be specified as an Allowed Callback URL in your application settings.
The service uses RxJS to emit changes in values to the
isAuthenticated state and the user's profile. These will be used in a moment to listen for changes and update the UI accordingly.
If you do not already have a logical place to house login and logout buttons within your application, create a new component to represent a navigation bar that can also hold some UI to log in and log out:
src/app/navbar/navbar.component.ts file and replace its contents with the following:
Notice that the
AuthService class you created in the previous section is being injected into the component through the constructor. This allows you to get an instance of the client, as well as react to changes in authentication state.
The main setup work is being carried out inside
ngOnInit, where the RxJS
BehaviorSubject instances are being used. Whenever the values of these change, the Navbar component will react to those changes and provide an updated UI. Functions are provided to log in and log out the user using
logout directly on the Auth0 client.
Next, configure the UI for the
navbar component by opening the
src/app/navbar/navbar.component.html file and replacing its contents with the following:
Angular bindings are used here to show each button at the right time; the Login button when the user is unauthenticated, and the Log Out button when the user has been authenticated. Their
click events are wired up to call the
logout functions on the component respectively.
Finally, to show this component on the screen, open the
src/app/app.component.html file and replace the default UI with the following:
Checkpoint: Run the application now using
npm start. The login button should be visible, and you should be able to click it to be redirected to Auth0 for login. If you log in and are redirected back to the app, you'll see an error in the console about a missing route. The callback route used when redirected back to the app is setup in the next section.
Handle Login Redirects
To log the user into your application, the redirect from Auth0 should be handled so that a proper login state can be achieved. To do this, the
handleLoginRedirect SDK method must be called when Auth0 redirects back to your application. This can be done by using a separate component to handle the redirect callback.
Use the Angular CLI to create a new component called
Open the newly-generated
src/app/callback/callback.component.ts file and replace its contents with the following:
Once again the
AuthService class is injected so that the component can gain access to the Auth0 SDK client. The key line is
await client.handleRedirectCallback, which processes the callback data from Auth0 and retrieves the tokens. It also sets some internal state that can be used to determine whether the user is authenticated or not.
Notice that the component updates the observable properties inside the
AuthService instance. This means that other components that are watching these observables can update their UI at the right time: when the user logs in.
This component also recovers the URL the user was trying to reach before redirecting to Auth0 for authentication. They are then redirected to that URL to continue their journey through the site.
In order for this component to work, the Angular router must be adjusted so that this component is used when the
/callback route is hit. Open
src/app/app-routing.module.ts and replace its content with the following:
The primary change here is to add in the
callback route which points to the
Checkpoint: Run the app again using
npm startin the terminal. This time you should be able to log in and have the application handle the callback appropriately, sending you back to the default route. The "log out" button should now be visible. Check that the "log out" button works and that the user is unauthenticated when clicked.
Showing Profile Information
Create a new component called "Profile" using the Angular CLI:
src/app/profile/profile.component.ts and replace its contents with the following:
In order to retrieve the profile data, the component subscribes to changes on the
profile property of
AuthService and sets a class-level property to its value. This property can be used to drive the UI and show the profile information on the screen.
To do this, open
src/app/profile/profile.component.html and replace its contents with the following:
This simple UI displays a JSON representation of the profile object, only if the
profile property on the component has a value. This means that the UI will be present if the user is logged in, and invisible if they are not.
To view the profile page, the router must be updated to show the profile component at the right time. Open
src/app/app-routing.module.ts and ensure that the
routes map includes a route to the your profile component:
Finally, update the navigation bar to include some router links so that we can navigate between the different pages. Open
src/app/navbar/navbar.component.html and update it to look like the following:
Run the application and log in. Click on the Profile link to browse to the
/profile URL. Your profile information should now be present on the screen in JSON format. Try logging out of the application again to make sure that the profile information disappears as you would expect.
Right now, your users could simply enter the
/profile path into their URL bar and reach the profile page, even if they're unauthenticated. You're going to use a Guard to help prevent that from happening.
Add an authentication guard
The Angular CLI can be used to generate a guard:
When asked the question "Which interfaces would you like to implement?", select "CanActivate".
src/app/auth.guard.ts file and replace its contents with the following:
The key part here is the implementation of the
canActivate method. First, the Auth0 client is retrieved. Then, the
isAuthenticated value is interrogated. If the user is already authenticated, then
true is returned to indicate that the current route can continue.
If the user is not authenticated, then the
loginWithRedirect method is invoked, causing the user to be logged in. Also notice that the
appState property in the options for
loginWithRedirect is set to an object containing a
target property. This value is set to the route that the user was trying to access when this guard was activated. We can use this to helpfully redirect the user to where they were trying to reach once they have successfully authenticated with Auth0.
In order for this guard to work, it must be applied to the router so that the
/profile route cannot be accessed unless the user is logged in. Open the
src/app/app-routing.module.ts file and update it so that the guard is used. It should look something like the following:
Check that the application works as intended, by logging out of the application, then trying to access
http://localhost:3000/profile route directly in the URL bar. You should be automatically redirected to the Auth0 Login page before being able to access your profile information in the app. Note that the application should automatically route you to the
/profile page after authentication.