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.
What can I use Rules for?
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 demonstrating how users can log in and log out with Auth0 and view profile information. It will also show you how to protect routes from unauthenticated users.
Create an Angular Application
If you do not already have your own application, a new one can be generated using the Angular CLI.
Install the CLI:
Then generate a new Angular application by running the following command from your filesystem wherever you'd like your application to be created:
When asked "Would you like to use Angular routing?", select y (yes).
Once the project has been created, open the
auth0-angular-demo folder in your favorite code editor.
By default, the Angular CLI serves your app on port
4200. This should run on port
3000 so that it matches the Auth0 URLs configured above. Open the
package.json file and modify the
start script to:
Install the SDK
While in the project folder, install the SDK using
npm in the terminal (or use one of the other methods from the section above):
Add an Authentication Service
To manage authentication with Auth0 throughout the application, create an authentication service. This way, authentication logic is consolidated in one place and can be injected easily.
Use the CLI to generate a new service called
src/app/auth.service.ts file inside your code editor and add the following content:
This service provides the properties and methods necessary to manage authentication across the application. An
auth0Client$ observable is defined that returns the same instance whenever a new subscription is created. The Auth0 SDK for Single Page Applications returns promises by default, so observables are then created for each SDK method so we can use reactive programming (RxJS) with authentication in our Angular app.
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 provides these methods:
getUser$(options)- Requests user data from the SDK and accepts an options parameter, then makes the user profile data available in a local RxJS stream
localAuthSetup()- On app initialization, manage authentication data in Angular; the session with Auth0 is checked to see if the user has logged in previously, and if so, they are re-authenticated on refresh without being prompted to log in again
login()- Log in with Auth0
handleAuthCallback()- Process the response from the authorization server when returning to the app after login
logout()- Log out of Auth0
Restore Login State When App Reloads
In a Single Page Application, when the user reloads the page anything stored in app memory is cleared. We don't want the application to force the user to log in again if they did not log out, and still have an active session with the authorization server.
In order to restore local authentication status after a refresh, we'll call the
localAuthSetup() method when the app initializes.
src/app/app.component.ts file and add the following:
We've imported the
OnInit lifecycle hook, implemented the interface in our
AppComponent class, provided the
AuthService in the constructor, and called
localAuthSetup() when the app component initializes.
localAuthSetup() method uses the
auth0-spa-js SDK to check if the user is still logged in with the authorization server. If they are, their authentication state is restored in the front end when they return to the app after refreshing or leaving, without having to log in again.
Users who are logged in with username/password will be silently reauthenticated automatically when the application reloads. No further action is needed for this type of login.
If you are using the classic Universal Login experience and would like users to authenticate using social identity providers (such as Google, Apple, Facebook, etc.), then you will need to configure those connections in your Auth0 Dashboard.
In the navigation menu, choose Connections - Social, and select the social connection you’d like to support. In the connection’s settings, click “How to obtain a Client ID?“ and follow the instructions to set up your own ID and secret.
If you are using the new Universal Login experience, the default enabled social connections will silently reauthenticate without additional configuration. However, you should still set up your own keys and avoid using default Auth0 development keys in a production app.
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:
AuthService class you created in the previous section is being provided in the component in the constructor. It is
public to enable use of its methods in the component template.
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:
Methods and properties from the authentication service are used to log in and log out, as well as show the appropriate button based on the user's current authentication state.
To display this component, 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 to authenticate. If you log in and are redirected back to the app, you'll see an error in the console about a missing route. We'll set up the callback redirection route next.
Handle Login Redirects
To authenticate the user, the redirect from Auth0 should be handled so that a proper login state can be achieved. To do this, the
handleAuthCallback() auth service method must be called when Auth0 redirects back to your application. This can be done in a component dedicated to this purpose.
Use the Angular CLI to create a new component called
src/app/callback/callback.component.ts file and replace its contents with the following:
AuthService class is injected so that the
handleAuthCallback() method can be called on initialization of the component.
In the authentication service,
handleAuthCallback() does several things:
- Stores the application route to redirect back to after login processing is complete
- Calls the JS SDK's
- Gets and sets the user's profile data
- Updates application login state
- After the callback has been processed, redirects the user to their intended route
Next, add the
/callback route to the app's routing module
Checkpoint: You should now be able to log in and have the application handle the callback appropriately, sending you back to the default route. The logout button should now be visible. Click the logout button to verify that it works.
Show 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:
All we need to do here is publicly inject the
AuthService so that it can be used in the template.
src/app/profile/profile.component.html and replace its contents with the following:
userProfile$ observable emits the user profile object when it becomes available in the application. By using the
async pipe, we can display the profile object as JSON once it's been emitted.
Next we need a route for the profile page. Open
src/app/app-routing.module.ts, import the
ProfileComponent, and add it to the
routes array to create a
Finally, the navigation bar should be updated to include navigation links. Open
src/app/navbar/navbar.component.html and add route links below the login/logout buttons:
Checkpoint: If you log in now, you should be able to click on the Profile link to access the
/profilepage component and view your user data. Log out of the application to make sure that the profile link is no longer displayed when unauthenticated.
Add an Authentication Guard
Right now, users could enter the
/profile path in the browser URL to view profile page, even if they're unauthenticated. They won't see any user data (since they're not logged in), but they can still access the page component itself. Let's fix this using a route guard.
The Angular CLI can be used to generate a guard:
You will receive this prompt: "Which interfaces would you like to implement?" Select CanActivate.
src/app/auth.guard.ts file and replace its contents with the following:
canActivate() method can return an
boolean. This tells the application whether or not navigation to the guarded route should be allowed to proceed depending on whether the returned value is
AuthService provides an observable that does exactly this, returning a boolean indicating if the user is authenticated:
We can return
isAuthenticated$ and implement a side effect with the
tap operator to check if the value is
false. If so, the user is not logged in, so we can call the
login() method to prompt the user to authenticate. Passing the
state.url as a parameter tells our authentication service's
login() function that we want the application to redirect back to this guarded URL after the user is logged in.
Now we need to apply the
AuthGuard to the
/profile route. Open the
src/app/app-routing.module.ts file and import the guard, then add it to the profile:
Checkpoint: Log out of your app and then navigate to
http://localhost:3000/profile. You should be automatically redirected to the Auth0 login page. Once you've authenticated successfully, you should be redirected to the