Angular: Login

Gravatar for steve.hobbs@auth0.com
By Steve Hobbs

This tutorial demonstrates how to add user login to an Angular application using Auth0. We recommend that you log in to follow this quickstart with examples configured for your account.

I want to explore a sample app

2 minutes

Get a sample configured with your account settings or check it out on Github.

View on Github
System requirements: Angular 12+

Configure Auth0

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.

App Dashboard

You need the following information:

  • Domain
  • 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 added to 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 added to 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 add the URL for your app to the Allowed Web Origins field in your Application Settings. If you don't register your application URL here, the application will be unable to silently refresh the authentication tokens and your users will be logged out the next time they visit the application, or refresh the page.

Install the Auth0 Angular SDK

Run the following command within your project directory to install the Auth0 Angular SDK:

npm install @auth0/auth0-angular

Was this helpful?

/

The SDK exposes several types that help you integrate Auth0 with your Angular application idiomatically, including a module and an authentication service.

Register and providing Auth0

The SDK exports provideAuth0, which is a provide function that contains all the services required for the SDK to function. To register this with your application:

  1. Open the main.ts file.
  2. Import the provideAuth0 function from the @auth0/auth0-angular package.
  3. Add provideAuth0 to the application by adding it to the providers inside bootstrapApplication.
  4. Inject AuthService into AppComponent.
import { bootstrapApplication } from '@angular/platform-browser';
import { provideAuth0 } from '@auth0/auth0-angular';
import { AppComponent } from './app.component';

bootstrapApplication(AppComponent, {
  providers: [
    provideAuth0({
      domain: '{yourDomain}',
      clientId: '{yourClientId}',
      authorizationParams: {
        redirect_uri: window.location.origin
      }
    }),
  ]
});

Was this helpful?

/

The provideAuth0 function takes the properties domain and clientId; the values of these properties correspond to the Domain and Client ID values that you can find under Settings in the Single-Page Application (SPA) that you registered with Auth0. On top of that, we configure authorizationParams.redirect_uri, which allows Auth0 to redirect the user back to the specific URL after successfully authenticating.

Checkpoint

Now that you have imported AuthModule, run your application to verify that the SDK is initializing correctly and that your application is not throwing any errors related to Auth0.

Add Login to Your Application

The Auth0 Angular SDK gives you tools to quickly implement user authentication in your Angular application, such as creating a login button using the loginWithRedirect() method from the AuthService service class. Executing loginWithRedirect() redirects your users to the Auth0 Universal Login Page, where Auth0 can authenticate them. Upon successful authentication, Auth0 will redirect your users back to your application.

import { Component } from '@angular/core';

// Import the AuthService type from the SDK
import { AuthService } from '@auth0/auth0-angular';

@Component({
  selector: 'app-auth-button',
  template: '<button (click)="auth.loginWithRedirect()">Log in</button>',
  standalone: true
})
export class AuthButtonComponent {
  // Inject the authentication service into your component through the constructor
  constructor(public auth: AuthService) {}
}

Was this helpful?

/

Checkpoint

Add the AuthButtonComponent component to your application. When you click it, verify that your Angular application redirects you to the Auth0 Universal Login page and that you can now log in or sign up using a username and password or a social provider.

Once that's complete, verify that Auth0 redirects back to your application's homepage.

Auth0 Universal Login

Add Logout to Your Application

Now that you can log in to your Angular application, you need a way to log out. You can create a logout button using the logout() method from the AuthService service. Executing logout() redirects your users to your Auth0 logout endpoint (https://YOUR_DOMAIN/v2/logout) and then immediately redirects them to your application.

Here is a modified version of the AuthButtonComponent component above that uses both loginWithRedirect() and logout(), as well as checking the authentication state using the isAuthenticated$ observable:

import { Component, Inject } from '@angular/core';
import { AuthService } from '@auth0/auth0-angular';
import { DOCUMENT } from '@angular/common';

@Component({
  selector: 'app-auth-button',
  template: `
    <ng-container *ngIf="auth.isAuthenticated$ | async; else loggedOut">
      <button (click)="auth.logout({ logoutParams: { returnTo: document.location.origin } })">
        Log out
      </button>
    </ng-container>

    <ng-template #loggedOut>
      <button (click)="auth.loginWithRedirect()">Log in</button>
    </ng-template>
  `,
  standalone: true
})
export class AuthButtonComponent {
  constructor(@Inject(DOCUMENT) public document: Document, public auth: AuthService) {}
}

Was this helpful?

/

Specify the returnTo option when calling logout to tell Auth0 where it should redirect to after a successful logout. This value must be specified in the Allowed Logout URLs setting in the dashboard.

Checkpoint

Add a button to the component template that logs the user out of your application. When you click it, verify that your Angular application redirects you the address you specified as one of the "Allowed Logout URLs" in the "Settings" and that you are no longer logged in to your application.

Show User Profile Information

The Auth0 Angular SDK helps you retrieve the profile information associated with logged-in users quickly in whatever component you need, such as their name or profile picture, to personalize the user interface. The profile information is available through the user$ observable exposed by the AuthService service. Take this Profile component as an example of how to use it:

import { Component } from '@angular/core';
import { AuthService } from '@auth0/auth0-angular';

@Component({
  selector: 'app-user-profile',
  template: `
    <ul *ngIf="auth.user$ | async as user">
      <li>{{ user.name }}</li>
      <li>{{ user.email }}</li>
    </ul>`,
  standalone: true
})
export class UserProfileComponent {
  constructor(public auth: AuthService) {}
}

Was this helpful?

/

The user$ observable contains sensitive information and artifacts related to the user's identity. As such, its availability depends on the user's authentication status. Fortunately, the user$ observable is configured so that it only starts to emit values once the isAuthenticated$ observable is true, so there is no need to manually check the authentication state before accessing the user profile data.

Checkpoint

Verify that you can display the user.name or any other user property within a component correctly after you have logged in.