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

> This guide demonstrates how to integrate Auth0 with any new or existing Blazor Server application using the Auth0.AspNetCore.Authentication SDK.

# Add Login to your Blazor Server 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 dark:text-black 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`}>
      {}
      <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-and-configure-the-sdk",
  title: "Install and Configure the SDK"
}, {
  id: "login",
  title: "Login"
}, {
  id: "display-user-profile",
  title: "Display User Profile"
}, {
  id: "logout",
  title: "Logout"
}];

<Recipe>
  <Content>
    Auth0 allows you to quickly add authentication and gain access to user profile information in your application.
    This guide demonstrates how to integrate Auth0 with any new or existing Blazor Server application using the
    **Auth0.AspNetCore.Authentication** SDK.

    <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/dashboard/us/auth0-dsepaid/), 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.

      <Info>
        If you are following along with our sample project, set this to
        `http://localhost:3000/callback`.
      </Info>

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

      <Info>
        If you are following along with our sample project, set this to `http://localhost:3000`.
      </Info>
    </Section>

    <Section id={sections[1].id} title={sections[1].title} stepNumber="2">
      ### Install from Nuget

      To integrate Auth0 with Blazor Server you can use our SDK by installing the
      `Auth0.AspNetCore.Authentication` [Nuget package](https://www.nuget.org/packages/Auth0.AspNetCore.Authentication/) to your application.

      ### Configure the middleware

      To enable authentication in your Blazor Server application, use the middleware provided by the SDK. Go to the
      `Program.cs` file and call `builder.Services.AddAuth0WebAppAuthentication()` to register the
      SDK's middleware.

      Ensure to configure the `Domain` and `ClientId`, these are required fields to ensure the
      SDK knows which Auth0 tenant and application it should use.

      Make sure you have enabled authentication and authorization in your `Program.cs` file.
    </Section>

    <Section id={sections[2].id} title={sections[2].title} stepNumber="3">
      To allow users to login to your Blazor Server application, add a `LoginModel` to your
      `Pages` directory.

      Inside the `LoginModel`'s `OnGet` method, call `HttpContext.ChallengeAsync()`
      and pass `Auth0Constants.AuthenticationScheme` as the authentication scheme. This will invoke the OIDC
      authentication handler that our SDK registers internally. Be sure to also specify the corresponding
      `authenticationProperties`, which you can construct using the
      `LoginAuthenticationPropertiesBuilder`.

      After successfully calling `HttpContext.ChallengeAsync()`, the user will be redirected to Auth0 and
      signed in to both the OIDC middleware and the cookie middleware upon being redirected back to your application.
      This will allow the users to be authenticated on subsequent requests.

      <Info>
        ##### Checkpoint

        Now that you have configured Login, run your application to verify that:

        * Navigating to your `Login` page will redirect to Auth0
        * Entering your credentials will redirect you back to your application.
      </Info>
    </Section>

    <Section id={sections[3].id} title={sections[3].title} stepNumber="4">
      After the middleware has successfully retrieved the tokens from Auth0, it will extract the user's information and
      claims from the ID Token and make them available through the `AuthenticationState`, which you can add
      as a `CascadingParameter`.

      You can create a custom user profile page for displaying the user's name, as well as additional claims (such as
      email and picture), by retrieving the corresponding information from the `AuthenticationState`'s
      `User` property and passing it to the view from inside Blazor code.

      <Info>
        ##### Checkpoint

        Now that you have set up to render the user's profile, run your application to verify that:

        * Navigating to the endpoint containing the profile after being successfully logged in shows the user's
          profile.
      </Info>
    </Section>

    <Section id={sections[4].id} title={sections[4].title} stepNumber="5">
      Logging out the user from your own application can be done by calling `HttpContext.SignOutAsync` with
      the `CookieAuthenticationDefaults.AuthenticationScheme` authentication scheme from inside a
      `LogoutModel`'s `OnGet` method.

      Additionally, if you also want to log the user out from Auth0 (this might also log them out of other applications
      that rely on Single Sign On), call `HttpContext.SignOutAsync` with the
      `Auth0Constants.AuthenticationScheme` authentication scheme as well as the appropriate
      `authenticationProperties` that can be constructed using the
      `LogoutAuthenticationPropertiesBuilder`.

      <Info>
        ##### Checkpoint

        Now that you have configured Logout, run your application to verify that:

        * Navigating to your `Logout` page will ensure the user is logged out.
        * When also logging out from Auth0, you should be redirected to Auth0 and instantly redirected back to
          your own application.
      </Info>
    </Section>

    ## Next Steps

    Excellent work! If you made it this far, you should now have login, logout, and user profile information running in your application.

    This concludes our quickstart tutorial, but there is so much more to explore. To learn more about what you can do with Auth0, check out:

    * [Auth0 Dashboard](https://manage.auth0.com/dashboard/us/dev-gja8kxz4ndtex3rq) - Learn how to configure and manage your Auth0 tenant and applications
    * [auth0-aspnetcore-authentication SDK](https://github.com/auth0/auth0-aspnetcore-authentication) - Explore the SDK used in this tutorial more fully
    * [Auth0 Marketplace](https://marketplace.auth0.com/) - Discover integrations you can enable to extend Auth0’s functionality
  </Content>

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

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

    <SideMenuSectionItem id={sections[2].id}>
      <CodeGroup>
        ```cs Login.cshtml.cs lines
        public class LoginModel : PageModel
        {
            public async Task OnGet(string redirectUri)
            {
                var authenticationProperties = new LoginAuthenticationPropertiesBuilder()
                    .WithRedirectUri(redirectUri)
                    .Build();

                await HttpContext.ChallengeAsync(Auth0Constants.AuthenticationScheme, authenticationProperties);
            }
        }
        ```

        ```cs Logout.cshtml.cs lines
        [Authorize]
        public class LogoutModel : PageModel
        {
            public async Task OnGet()
            {
                var authenticationProperties = new LogoutAuthenticationPropertiesBuilder()
                    .WithRedirectUri("/")
                    .Build();

                await HttpContext.SignOutAsync(Auth0Constants.AuthenticationScheme, authenticationProperties);
                await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            }
        }
        ```
      </CodeGroup>
    </SideMenuSectionItem>

    <SideMenuSectionItem id={sections[3].id}>
      <CodeGroup>
        ```cs Login.cshtml.cs lines
        public class LoginModel : PageModel
        {
            public async Task OnGet(string redirectUri)
            {
                var authenticationProperties = new LoginAuthenticationPropertiesBuilder()
                    .WithRedirectUri(redirectUri)
                    .Build();

                await HttpContext.ChallengeAsync(Auth0Constants.AuthenticationScheme, authenticationProperties);
            }
        }
        ```

        ```cs Logout.cshtml.cs lines
        [Authorize]
        public class LogoutModel : PageModel
        {
            public async Task OnGet()
            {
                var authenticationProperties = new LogoutAuthenticationPropertiesBuilder()
                    .WithRedirectUri("/")
                    .Build();

                await HttpContext.SignOutAsync(Auth0Constants.AuthenticationScheme, authenticationProperties);
                await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            }
        }
        ```
      </CodeGroup>
    </SideMenuSectionItem>

    <SideMenuSectionItem id={sections[4].id}>
      <CodeGroup>
        ```cs Logout.cshtml.cs lines
        [Authorize]
        public class LogoutModel : PageModel
        {
            public async Task OnGet()
            {
                var authenticationProperties = new LogoutAuthenticationPropertiesBuilder()
                    .WithRedirectUri("/")
                    .Build();

                await HttpContext.SignOutAsync(Auth0Constants.AuthenticationScheme, authenticationProperties);
                await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            }
        }
        ```

        ```cs Login.cshtml.cs lines
        public class LoginModel : PageModel
        {
            public async Task OnGet(string redirectUri)
            {
                var authenticationProperties = new LoginAuthenticationPropertiesBuilder()
                    .WithRedirectUri(redirectUri)
                    .Build();

                await HttpContext.ChallengeAsync(Auth0Constants.AuthenticationScheme, authenticationProperties);
            }
        }
        ```
      </CodeGroup>
    </SideMenuSectionItem>
  </SideMenu>
</Recipe>
