Docs

Angular: Login

View on Github

Angular: Login

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.

System requirements: Angular 7+

New to Auth? Learn How Auth0 works, how it integrates with Single-Page Applications and which protocol it uses.

Use RSA algorithm for JWTs

Configure Auth0

Keep reading

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:

  • Domain
  • Client ID

If you download the sample from the top of this page these details are filled out for you.

If you have more than one application in your account, the sample comes with the values for your Default App.

App Dashboard

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.

If you are following along with the sample project you downloaded from the top of this page, you should set the Allowed Callback URL to http://localhost:3000/callback.

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.

If you are following along with the sample project you downloaded from the top of this page, the logout URL you need to whitelist in the Allowed Logout URLs field is http://localhost:3000.

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.

If you are following along with the sample project you downloaded from the top of this page, you should set the Allowed Web Origins to http://localhost:3000.

Integrate Auth0 in your Application

Loading auth0-spa-js

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

Install auth0-spa-js using npm or yarn.

Once 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.

If you encounter some problems or errors when using the new JavaScript SDK, please check out the FAQ to see if your issue is covered there.

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.

You can also embed the login dialog directly in your application using the Lock widget. If you use this method, some features, such as single sign-on, will not be accessible.

When a user logs in, Auth0 returns three items:

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.

This tutorial assumes that you're able to use the Angular CLI to generate new components and services on your project. If not, please place the files where appropriate and ensure that any references to them regarding import paths are correct for your scenario.

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:

If you are following this tutorial using your own Angular application that runs on a different port, you should modify the URLs above when configuring Auth0 so that they match the host and port number of your own application.

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 AuthService:

Open the src/app/auth.service.ts file inside your code editor and add the following content:

Make sure that the domain and client ID values are correct for the application that you want to connect with.

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

Why is there so much RxJS in the authentication service? auth0-spa-js is a promise-based library built using async/await, providing an agnostic approach for the highest volume of JavaScript apps. The Angular framework, on the other hand, uses reactive programming and observable streams. In order for the async/await library to work seamlessly with Angular’s stream-based approach, we are converting the async/await functionality to observables for you in the service.

Auth0 is currently building an Angular module that will abstract this reactive functionality into an importable wrapper. This will get you up and running even faster while using the most idiomatic approach for the Angular framework, and will greatly simplify the authentication service.

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.

We also should not store sensitive session data in browser storage due to lack of security.

In order to restore local authentication status after a refresh, we'll call the localAuthSetup() method when the app initializes.

Open the 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.

The 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.

Restoring Login State with Social Providers

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.

Create a Navigation Bar Component

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:

Open the src/app/navbar/navbar.component.ts file and replace its contents with the following:

The 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 Callback:

Open the src/app/callback/callback.component.ts file and replace its contents with the following:

The 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 handleRedirectCallback method
  • 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 src/app/app-routing.module.ts:

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:

Open 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.

Next, open src/app/profile/profile.component.html and replace its contents with the following:

The AuthService's 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 /profile route:

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 /profile page 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.

Open the src/app/auth.guard.ts file and replace its contents with the following:

The canActivate() method can return an observable<boolean>, promise<boolean>, or 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 true or false.

The AuthService provides an observable that does exactly this, returning a boolean indicating if the user is authenticated: isAuthenticated$.

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:

Guards are arrays because multiple guards can be added to the same route. They will run in the order declared in the array.

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 /profile page.

Use Auth0 for FREE