> ## Documentation Index
> Fetch the complete documentation index at: https://auth0-cq3uo.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Add Login to Your Angular Application

export const SignUpForm = () => {
  return <div className="flex flex-col gap-2 items-center h-full">
      <img noZoom src="/docs/img/quickstarts/action_hero_dashboard.svg" alt="Sign up for an Auth0 account" style={{
    width: "250px",
    height: "250px"
  }} />
      <span className="text-center" style={{
    width: "400px"
  }}>
        Sign up for an{" "}
        <a href="https://auth0.com/signup" target="_blank" rel="noopener noreferrer">
          Auth0 account
        </a>{" "}
        or{" "}
        <span className="font-semibold text-primary cursor-pointer" onClick={() => console.log("log in")}>
          log in
        </span>{" "}
        to your existing account to integrate directly with your own tenant.
      </span>
      <button onClick={() => console.log("sign up")} className="bg-primary dark:bg-primary-light text-white px-4 py-2 rounded-md mt-4 font-medium" style={{
    width: "140px"
  }}>
        Sign up
      </button>
    </div>;
};

export const SideMenuSectionItem = ({id, children}) => {
  return <div id={`side-menu-item-${id}`} className="recipe-side-menu-item flex flex-col w-full h-full">
      {children}
    </div>;
};

export const SideMenu = ({sections, children}) => {
  const [visibleSection, setVisibleSection] = useState(sections[0]?.id ?? null);
  const checkVisibility = () => {
    let currentVisible = null;
    const viewportHeight = window.innerHeight;
    const scrollY = window.scrollY;
    sections.forEach(({id}) => {
      const section = document.getElementById(id);
      if (section) {
        const rect = section.getBoundingClientRect();
        const sectionTop = rect.top + scrollY;
        const sectionBottom = sectionTop + rect.height;
        const multiplier = viewportHeight > 1600 ? 0.34 : 0.22;
        if (scrollY + viewportHeight * multiplier >= sectionTop && scrollY <= sectionBottom) {
          currentVisible = id;
        }
      }
    });
    if (currentVisible && currentVisible !== visibleSection) {
      setVisibleSection(currentVisible);
    }
  };
  useEffect(() => {
    const throttledCheck = () => {
      setTimeout(checkVisibility, 100);
    };
    checkVisibility();
    window.addEventListener("scroll", throttledCheck);
    return () => {
      window.removeEventListener("scroll", throttledCheck);
    };
  }, [sections, visibleSection]);
  useEffect(() => {
    sections.forEach(({id}) => {
      const section = document.getElementById(id);
      const sideMenuItem = document.getElementById(`side-menu-item-${id}`);
      if (section) {
        if (id === visibleSection) {
          section.classList.add("active-section");
        } else {
          section.classList.remove("active-section");
        }
      }
      if (sideMenuItem) {
        if (id === visibleSection) {
          sideMenuItem.classList.add("active-side-menu-item");
        } else {
          sideMenuItem.classList.remove("active-side-menu-item");
        }
      }
    });
  }, [visibleSection, sections]);
  return <div className="recipe-side-menu sticky px-2 py-1" style={{
    height: "calc(100vh - 7rem)",
    top: "7rem",
    scrollMarginTop: "var(--scroll-mt)"
  }}>
      {children.map(child => {
    if (child.props.id === visibleSection) {
      return child;
    }
    return null;
  })}
    </div>;
};

export const Section = ({id, title, stepNumber, children, isSingleColumn = false}) => {
  return <div id={id} className={`recipe-section flex flex-col transition-opacity duration-200 ${isSingleColumn ? "opacity-100 dark:opacity-100" : "opacity-60 dark:opacity-60"}`}>
      <Step title={title} stepNumber={stepNumber} titleSize="h3">
        {children}
      </Step>
    </div>;
};

export const Content = ({title, children}) => {
  return <div className="recipe-content flex flex-col">
      {title && <h1 className="text-3xl">{title}</h1>}
      {children}
    </div>;
};

export const Recipe = ({children, isSingleColumn = false}) => {
  return <div className={`pl-4 recipe-container mx-auto grid grid-cols-1 gap-10 relative ${isSingleColumn ? "md:grid-cols-1" : "md:grid-cols-2"}`}>
      {children}
    </div>;
};

export const sections = [{
  id: "configure-auth0",
  title: "Configure Auth0"
}, {
  id: "install-the-auth0-angular-sdk",
  title: "Install the Auth0 Angular SDK"
}, {
  id: "register-and-providing-auth0",
  title: "Register and providing Auth0"
}, {
  id: "add-login-to-your-application",
  title: "Add login to your application"
}, {
  id: "add-logout-to-your-application",
  title: "Add logout to your application"
}, {
  id: "show-user-profile-information",
  title: "Show user profile information"
}];

<Recipe>
  <Content>
    <Callout icon="file-lines" iconType="regular">
      Visit the [Angular Authentication By Example](https://developer.auth0.com/resources/guides/spa/angular/basic-authentication) guide for a deep dive
      into implementing user authentication in Angular. This guide provides additional details on how to create
      a sign-up button, add route guards, and call a protected API from Angular.
    </Callout>

    Auth0 allows you to add authentication to almost any application type quickly. This guide demonstrates how to
    integrate Auth0, add authentication, and display user profile information in any Angular application using the [Auth0 Angular SDK](https://github.com/auth0/auth0-angular).

    To use this quickstart, you’ll need to:

    * Sign up for a free Auth0 account or log in to Auth0.
    * Have a working Angular project that you want to integrate with. Alternatively, you can view or download a sample application after logging in.

    <Section id={sections[0].id} title={sections[0].title} stepNumber="1">
      To use Auth0 services, you’ll need to have an application set up in the Auth0 Dashboard. The Auth0 application is
      where you will configure how you want authentication to work for the project you are developing.

      ### Configure an application

      Use the interactive selector to create a new Auth0 application or select an existing application that represents
      the project you want to integrate with. Every application in Auth0 is assigned an alphanumeric, unique client ID
      that your application code will use to call Auth0 APIs through the SDK.

      Any settings you configure using this quickstart will automatically update for your Application in the [Dashboard](https://manage.auth0.com/#/), which is where you
      can manage your Applications in the future.

      If you would rather explore a complete configuration, you can view a sample application instead.

      ### Configure Callback URLs

      A callback URL is a URL in your application that you would like Auth0 to redirect users to after they have
      authenticated. If not set, users will not be returned to your application after they log in.

      <Callout icon="file-lines" iconType="regular">
        If you are following along with our sample project, set this to `http://localhost:4200`.
      </Callout>

      ### Configure Logout URLs

      A logout URL is a URL in your application that you would like Auth0 to redirect users to after they have logged
      out. If not set, users will not be able to log out from your application and will receive an error.

      <Callout icon="file-lines" iconType="regular">
        If you are following along with our sample project, set this to `http://localhost:4200`.
      </Callout>

      ### Configure Allowed Web Origins

      An Allowed Web Origin is a URL that you want to be allowed to access to your authentication flow. This must
      contain the URL of your project. If not properly set, your project will be unable to silently refresh
      authentication tokens, so your users will be logged out the next time they visit your application or refresh a
      page.

      <Callout icon="file-lines" iconType="regular">
        If you are following along with our sample project, set this to `http://localhost:4200`.
      </Callout>
    </Section>

    <Section id={sections[1].id} title={sections[1].title} stepNumber="2">
      Auth0 provides an [Angular SDK](https://github.com/auth0/auth0-angular) to simplify the process of implementing Auth0 authentication and
      authorization in Angular applications.

      Install the Auth0 Angular SDK by running the following command in your terminal:

      ```bash lines theme={null}
      npm install @auth0/auth0-angular
      ```

      The SDK exposes several types that help integrate Auth0 in an Angular application idiomatically, including a
      module and an authentication service.
    </Section>

    <Section id={sections[2].id} title={sections[2].title} stepNumber="3">
      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`.

      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.

      <Callout icon="file-lines" iconType="regular">
        If you are using a [custom domain with
        Auth0](https://auth0.com/docs/custom-domains), the value of the domain property is the value of your custom domain instead of the value
        reflected in the "Settings" tab.
      </Callout>
    </Section>

    <Section id={sections[3].id} title={sections[3].title} stepNumber="4">
      Now that you have configured your Auth0 Application and the Auth0 Angular SDK, you need to set up login for your
      project. To do this, you will use the SDK’s `loginWithRedirect()` method from the
      `AuthService` class to redirect users to the Auth0 Universal Login page where Auth0 can authenticate
      them. After a user successfully authenticates, they will be redirected to your application and the callback URL
      you set up earlier in this quickstart.

      Create a login button in your application that calls `loginWithRedirect()` when selected.

      <Callout icon="file-lines" color="#0EA5E9" iconType="regular">
        ##### Checkpoint

        You should now be able to log in to your application.

        Run your application, and select the login button. Verify that:

        * you can log in or sign up using a username and password.
        * your application redirects you to the [Auth0 Universal Login](https://auth0.com/universal-login) page.
        * you are redirected to Auth0 for authentication.
        * Auth0 successfully redirects back to your application after authentication.
        * you do not receive any errors in the console related to Auth0.
      </Callout>
    </Section>

    <Section id={sections[4].id} title={sections[4].title} stepNumber="5">
      Users who log in to your project will also need [a way to log out](https://auth0.com/docs/logout/guides/logout-auth0). The SDK provides a `logout()` method on the
      `AuthService` class that you can use to log a user out of your app. When users log out, they will be
      redirected to your [Auth0
      logout endpoint](https://auth0.com/docs/api/authentication?javascript#logout), which will then immediately redirect them to your application and the logout URL you set up
      earlier in this quickstart.

      Create a logout button in your application that calls `logout()` when selected.

      <Callout icon="file-lines" iconType="regular">
        The SDK exposes an `isAuthenticated$` observable on the `AuthService` class that
        allows you to check whether a user is authenticated or not. You can render the login and logout buttons
        conditionally based on the value of the `isAuthenticated$` observable. Alternatively, you can
        use a single button to combine both login and logout buttons as well as their conditional rendering.
      </Callout>

      <Callout icon="file-lines" color="#0EA5E9" iconType="regular">
        ##### Checkpoint

        You should now be able to log out of your application.

        Run your application, log in, and select the logout button. Verify that:

        * you are redirected to Auth0's logout endpoint.
        * Auth0 successfully redirects back to your application and the correct logout URL.
        * you are no longer logged in to your application.
        * you do not receive any errors in the console related to Auth0.
      </Callout>
    </Section>

    <Section id={sections[5].id} title={sections[5].title} stepNumber="6">
      Now that your users can log in and log out, you will likely want to be able to retrieve the [profile information](https://auth0.com/docs/users/concepts/overview-user-profile)
      associated with authenticated users. For example, you may want to be able to personalize the user interface by
      displaying a logged-in user’s name or profile picture.

      The Auth0 Angular SDK provides user information through the `user$` observable exposed by the
      `AuthService` class. Because the `user$` observable contains sensitive information and
      artifacts related to the user's identity, its availability depends on the user's authentication status.
      Fortunately, the `user$` observable is configured to only 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.

      The SDK also exposes an `isAuthenticated$` observable on the `AuthService` class that
      allows you to check whether a user is authenticated or not, which you can use to determine whether to show or hide
      UI elements, for example.

      Review the `UserProfileComponent` code in the interactive panel to see examples of how to use these
      functions.

      <Callout icon="file-lines" color="#0EA5E9" iconType="regular">
        ##### Checkpoint

        You should now be able to view user profile information.

        Run your application, and verify that:

        * user information displays correctly after you have logged in.
        * user information does not display after you have logged out.
      </Callout>
    </Section>
  </Content>

  <SideMenu sections={sections}>
    <SideMenuSectionItem id={sections[0].id}>
      <SignUpForm />
    </SideMenuSectionItem>

    <SideMenuSectionItem id={sections[1].id}>
      <SignUpForm />
    </SideMenuSectionItem>

    <SideMenuSectionItem id={sections[2].id}>
      <CodeGroup>
        ```tsx main.ts highlight={7-13} lines theme={null}
        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
              }
            }),
          ]
        });
        ```

        ```tsx login-button.ts highlight={11-13} lines theme={null}
        import { Component } from '@angular/core';
        import { AuthService } from '@auth0/auth0-angular';

        @Component({
          selector: 'app-login-button',
          template: '<button (click)="login()">Log in</button>',
          standalone: true
        })
        export class LoginButtonComponent {
          constructor(private auth: AuthService) {}

          login() {
            this.auth.loginWithRedirect();
          }
        }
        ```

        ```tsx logout-button.ts highlight={19-25} lines theme={null}
        import { Component, Inject } from '@angular/core';
        import { AuthService } from '@auth0/auth0-angular';
        import { DOCUMENT } from '@angular/common';

        @Component({
          selector: 'app-logout-button',
          template: `
            <button (click)="logout()">
              Log out
            </button>
          `,
          standalone: true
        })
        export class LogoutButtonComponent {
          constructor(
            @Inject(DOCUMENT) public document: Document,
            private auth: AuthService
          ) {}

          logout() {
            this.auth.logout({ 
              logoutParams: {
                returnTo: this.document.location.origin 
              }
            });
          }
        }
        ```

        ```tsx user-profile.ts lines theme={null}
        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) {}
        }
        ```
      </CodeGroup>
    </SideMenuSectionItem>

    <SideMenuSectionItem id={sections[3].id}>
      <CodeGroup>
        ```tsx login-button.ts highlight={11-13} lines theme={null}
        import { Component } from '@angular/core';
        import { AuthService } from '@auth0/auth0-angular';

        @Component({
          selector: 'app-login-button',
          template: '<button (click)="login()">Log in</button>',
          standalone: true
        })
        export class LoginButtonComponent {
          constructor(private auth: AuthService) {}

          login() {
            this.auth.loginWithRedirect();
          }
        }
        ```

        ```tsx main.ts highlight={7-13} lines theme={null}
        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
              }
            }),
          ]
        });
        ```

        ```tsx logout-button.ts highlight={19-25} lines theme={null}
        import { Component, Inject } from '@angular/core';
        import { AuthService } from '@auth0/auth0-angular';
        import { DOCUMENT } from '@angular/common';

        @Component({
          selector: 'app-logout-button',
          template: `
            <button (click)="logout()">
              Log out
            </button>
          `,
          standalone: true
        })
        export class LogoutButtonComponent {
          constructor(
            @Inject(DOCUMENT) public document: Document,
            private auth: AuthService
          ) {}

          logout() {
            this.auth.logout({ 
              logoutParams: {
                returnTo: this.document.location.origin 
              }
            });
          }
        }
        ```

        ```tsx user-profile.ts lines theme={null}
        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) {}
        }
        ```
      </CodeGroup>
    </SideMenuSectionItem>

    <SideMenuSectionItem id={sections[4].id}>
      <CodeGroup>
        ```tsx logout-button.ts highlight={19-25} lines theme={null}
        import { Component, Inject } from '@angular/core';
        import { AuthService } from '@auth0/auth0-angular';
        import { DOCUMENT } from '@angular/common';

        @Component({
          selector: 'app-logout-button',
          template: `
            <button (click)="logout()">
              Log out
            </button>
          `,
          standalone: true
        })
        export class LogoutButtonComponent {
          constructor(
            @Inject(DOCUMENT) public document: Document,
            private auth: AuthService
          ) {}

          logout() {
            this.auth.logout({ 
              logoutParams: {
                returnTo: this.document.location.origin 
              }
            });
          }
        }
        ```

        ```tsx main.ts highlight={7-13} lines theme={null}
        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
              }
            }),
          ]
        });
        ```

        ```tsx login-button.ts highlight={11-13} lines theme={null}
        import { Component } from '@angular/core';
        import { AuthService } from '@auth0/auth0-angular';

        @Component({
          selector: 'app-login-button',
          template: '<button (click)="login()">Log in</button>',
          standalone: true
        })
        export class LoginButtonComponent {
          constructor(private auth: AuthService) {}

          login() {
            this.auth.loginWithRedirect();
          }
        }
        ```

        ```tsx user-profile.ts lines theme={null}
        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) {}
        }
        ```
      </CodeGroup>
    </SideMenuSectionItem>

    <SideMenuSectionItem id={sections[5].id}>
      <CodeGroup>
        ```tsx user-profile.ts lines theme={null}
        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) {}
        }
        ```

        ```tsx main.ts highlight={7-13} lines theme={null}
        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
              }
            }),
          ]
        });
        ```

        ```tsx login-button.ts highlight={11-13} lines theme={null}
        import { Component } from '@angular/core';
        import { AuthService } from '@auth0/auth0-angular';

        @Component({
          selector: 'app-login-button',
          template: '<button (click)="login()">Log in</button>',
          standalone: true
        })
        export class LoginButtonComponent {
          constructor(private auth: AuthService) {}

          login() {
            this.auth.loginWithRedirect();
          }
        }
        ```

        ```tsx logout-button.ts highlight={19-25} lines theme={null}
        import { Component, Inject } from '@angular/core';
        import { AuthService } from '@auth0/auth0-angular';
        import { DOCUMENT } from '@angular/common';

        @Component({
          selector: 'app-logout-button',
          template: `
            <button (click)="logout()">
              Log out
            </button>
          `,
          standalone: true
        })
        export class LogoutButtonComponent {
          constructor(
            @Inject(DOCUMENT) public document: Document,
            private auth: AuthService
          ) {}

          logout() {
            this.auth.logout({ 
              logoutParams: {
                returnTo: this.document.location.origin 
              }
            });
          }
        }
        ```
      </CodeGroup>
    </SideMenuSectionItem>
  </SideMenu>
</Recipe>
