Angular: Login

View on Github

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 configure the authentication module

The SDK exports AuthModule, a module that contains all the services required for the SDK to function. To register this with your application:

  • Open the app.module.ts file
  • Import the AuthModule type from the @auth0/auth0-angular package
  • Add AuthModule to the application by calling AuthModule.forRoot and adding to your application module's imports array
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

// Import the module from the SDK
import { AuthModule } from '@auth0/auth0-angular';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,

    // Import the module into the application, with configuration
    AuthModule.forRoot({
      domain: '{yourDomain}',
      clientId: '{yourClientId}',
      authorizationParams: {
        redirect_uri: window.location.origin
      }
    }),
  ],

  bootstrap: [AppComponent],
})
export class AppModule {}

Was this helpful?

/

We use the forRoot() pattern to configure the module, which takes the properties domain and clientId; the values of these properties correspond to the "Domain" and "Client ID" values present under the "Settings" of the single-page application 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>'
})
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>
  `,
  styles: [],
})
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>`
})
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.

Use Auth0 for FREE