# FusionAuth QuickStart for .NET

Learn how to add FusionAuth login to an ASP.NET Core Razor Pages app.

> For the index of this section of the site, see [llms.txt](https://fusionauth.io/docs/llms.txt)

![.NET](https://fusionauth.io/img/icons/dotnet-c.svg)

This QuickStart explains how to add a login page and authentication to a website built with [ASP.NET Core Razor Pages](https://learn.microsoft.com/en-us/aspnet/core/razor-pages/). You'll begin with a simple Razor Pages app that allows visitors to edit a file. Then, you'll add authentication to the app with a FusionAuth instance. Finally, you'll extend the app to handle multiple independent users with user data provided by FusionAuth.

This tutorial should take between 5 and 15 minutes; less if you already have prerequisites like Docker installed.

## Prerequisites

This QuickStart requires:

*   [.NET SDK](https://dotnet.microsoft.com/en-us/download/dotnet/10.0) 10 or later
*   [Docker](https://docs.docker.com/get-started/get-docker/) 23 or later

If you use macOS or Windows, you need one of the following container management tools:

*   [Docker Desktop](https://www.docker.com/products/docker-desktop/)
*   [OrbStack](https://docs.orbstack.dev/quick-start) (to use OrbStack for `docker compose` commands after installation, run `docker context use orbstack`)
*   [Podman](https://podman.io/docs/installation) (in the commands below, replace `docker` with `podman`)

## Create a Simple .NET App

For this QuickStart, we'll use a Razor Pages app that reads and writes data to a text file:

1.  Create a folder for the app and navigate into it:
    
    ```shell-session
    $ mkdir dotnet-quickstart && cd dotnet-quickstart
    ```
    
2.  Create a Razor Pages project named `Notes` in the current folder:
    
    ```shell-session
    $ dotnet new webapp -n Notes -o . -f net10.0 --no-https
    ```
    
    This creates a `Notes.csproj` file, a `Program.cs` file, and a `Pages` folder with the app's pages.
    
3.  Replace the contents of `Pages/Index.cshtml.cs` with the following code:
    
    ```csharp
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    
    namespace Notes.Pages;
    
    public class IndexModel : PageModel
    {
        public string Note { get; private set; } = "";
    
        private string NotePath => "note.txt";
    
        public void OnGet()
        {
            Note = System.IO.File.Exists(NotePath)
                ? System.IO.File.ReadAllText(NotePath)
                : "";
        }
    
        public IActionResult OnPost(string? content)
        {
            System.IO.File.WriteAllText(NotePath, content ?? "");
            return RedirectToPage();
        }
    }
    ```
    
    `OnGet` reads the note when the page loads, and `OnPost` saves it when the form is submitted.
    
4.  Replace the contents of `Pages/Index.cshtml` with the following code, which displays the note in a form:
    
    ```razor
    @page
    @model Notes.Pages.IndexModel
    @{
        Layout = null;
    }
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Notes</title>
    </head>
    <body>
        <h1>Notes</h1>
        <form method="post" asp-page="/Index">
            <label for="content">Your note</label><br>
            <textarea id="content" name="content" rows="8" cols="40">@Model.Note</textarea><br>
            <button type="submit">Save Changes</button>
        </form>
    </body>
    </html>
    ```
    
    The form uses the `asp-page` tag helper, which adds the token ASP.NET Core uses to prevent [CSRF](https://fusionauth.io/docs/apis/oauth/authorize.md).
    
5.  Run the app:
    
    ```shell-session
    $ dotnet run --urls http://localhost:3000
    ```
    
6.  Open the app at [http://localhost:3000](http://localhost:3000).
    
7.  Type "Hello .NET" in the text area, then click Save Changes .
    
8.  In a file browser or terminal, look in the `dotnet-quickstart` folder. You should see a new file named `note.txt`, with text content "Hello .NET".
    
9.  Press **Ctrl+C** on your keyboard to stop the app.
    

## Install and Run FusionAuth

Before we can add authentication to our .NET app, we need a local FusionAuth instance:

1.  Open your container management tool (listed in the prerequisites above).
    
2.  From the `dotnet-quickstart` folder, clone the [GitHub repository for the FusionAuth instance you'll use with this QuickStart](https://github.com/FusionAuth/fusionauth-quickstart-app):
    
    ```shell-session
    $ git clone https://github.com/FusionAuth/fusionauth-quickstart-app.git
    ```
    
3.  Navigate into the cloned directory:
    
    ```shell-session
    $ cd fusionauth-quickstart-app
    ```
    
4.  To start a local instance of FusionAuth, run the following command (omit the `-d` flag to see all Docker logs):
    
    ```shell-session
    $ docker compose up -d
    ```
    
5.  Wait until all networks, volumes, and containers show a green status of **Healthy**, **Started**, or **Created**. This may take a few minutes, depending on your network speed and cached dependencies.
    
6.  Open [http://localhost:9011/admin](http://localhost:9011/admin) to access the FusionAuth Admin UI.
    
7.  Log in with these credentials:
    
    *   username: `admin@example.com`
    *   password: `password`
8.  Navigate to Applications -> QuickStart App -> Edit -> OAuth . On this page, you can find your client Id and client secret, and set redirect and logout URLs. In the next part of this QuickStart, we'll use these values to connect our .NET app with FusionAuth.
    
9.  Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our .NET app, and because FusionAuth supports SSO, we need to log out of our admin account before we can log in as a normal user.
    

## Add FusionAuth to the .NET App

Now that you have a working instance of FusionAuth and a working .NET app, let's use FusionAuth to add login to your .NET app:

1.  Navigate out of the `fusionauth-quickstart-app` folder, back to the `dotnet-quickstart` folder that contains `Notes.csproj` and `note.txt`:
    
    ```shell-session
    $ cd ..
    ```
    
2.  Install the ASP.NET Core OpenID Connect package, which handles communication with our FusionAuth instance:
    
    ```shell-session
    $ dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect --version 10.0.15
    ```
    
3.  Replace the contents of `appsettings.Development.json` with the following configuration (we provided the same configuration for the local FusionAuth instance, and then viewed it in the Admin UI):
    
    ```json
    {
      "FusionAuth": {
        "Authority": "http://localhost:9011",
        "ClientId": "f0510a74-da7a-4101-a474-05e7f1d5ba7e",
        "ClientSecret": "super-secret-secret-that-should-be-regenerated-for-production"
      }
    }
    ```
    
4.  Replace the contents of `Program.cs` with the following code:
    
    ```csharp
    using Microsoft.AspNetCore.Authentication;
    using Microsoft.AspNetCore.Authentication.Cookies;
    using Microsoft.AspNetCore.Authentication.OpenIdConnect;
    using Microsoft.IdentityModel.Protocols.OpenIdConnect;
    
    var builder = WebApplication.CreateBuilder(args);
    var fusionAuth = builder.Configuration.GetSection("FusionAuth");
    
    builder.Services.AddRazorPages();
    builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options => options.LoginPath = "/login")
        .AddOpenIdConnect(options =>
        {
            options.Authority = fusionAuth["Authority"];
            options.ClientId = fusionAuth["ClientId"];
            options.ClientSecret = fusionAuth["ClientSecret"];
            options.ResponseType = OpenIdConnectResponseType.Code;
            options.UsePkce = true;
            options.RequireHttpsMetadata = !builder.Environment.IsDevelopment();
            options.CallbackPath = "/oauth-callback";
            options.MapInboundClaims = false;
            options.Scope.Clear();
            options.Scope.Add("openid");
            options.SaveTokens = true;
            options.Events.OnRedirectToIdentityProviderForSignOut = context =>
            {
                context.ProtocolMessage.PostLogoutRedirectUri = "http://localhost:3000/login";
                return Task.CompletedTask;
            };
        });
    
    var app = builder.Build();
    app.UseAuthentication();
    app.UseAuthorization();
    app.MapRazorPages();
    app.MapGet("/login/start", () => Results.Challenge(
        new AuthenticationProperties { RedirectUri = "/" },
        [OpenIdConnectDefaults.AuthenticationScheme]));
    app.Run();
    ```
    
    The new code connects the app to FusionAuth:
    
    *   `AddCookie` keeps the user logged in to the app with a cookie, and sends users who aren't logged in to `/login`.
    *   `AddOpenIdConnect` tells ASP.NET Core how to talk to FusionAuth. It uses the client Id, client secret, and [PKCE](https://fusionauth.io/docs/authentication/oauth/authorization-code.md#proof-key-for-code-exchange), and finds the login and token endpoints in the OpenID Connect discovery document at `/.well-known/openid-configuration`. `RequireHttpsMetadata` is turned off in development so the app can read that document from the local FusionAuth instance over HTTP.
    *   `CallbackPath` sets `/oauth-callback` as the route that receives the authorization code from FusionAuth. The handler exchanges the code for tokens, validates the [ID token](https://fusionauth.io/docs/authentication/oauth/tokens.md#id-token), and signs the user in to the cookie session.
    *   `MapInboundClaims = false` keeps the claim names from the ID token, such as `sub`, instead of renaming them to .NET claim types.
    *   `SaveTokens` keeps the ID token, which the handler sends to FusionAuth when the user logs out. The `OnRedirectToIdentityProviderForSignOut` event sends the user back to the login page after FusionAuth ends their session.
    *   The `/login/start` route starts the OpenID Connect challenge, which sends the user to the FusionAuth login page.
5.  Create a file named `Pages/Login.cshtml` with the following code, which links to `/login/start`:
    
    ```razor
    @page "/login"
    @{
        Layout = null;
    }
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Log in</title>
    </head>
    <body>
        <h1>Log in to Notes</h1>
        <a href="/login/start">Log in with FusionAuth</a>
    </body>
    </html>
    ```
    
6.  Replace the contents of `Pages/Index.cshtml.cs` with the following code:
    
    ```csharp
    using Microsoft.AspNetCore.Authentication.Cookies;
    using Microsoft.AspNetCore.Authentication.OpenIdConnect;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    
    namespace Notes.Pages;
    
    [Authorize]
    public class IndexModel : PageModel
    {
        public string Note { get; private set; } = "";
    
        private string NotePath => "note.txt";
    
        public IActionResult OnPostLogout()
        {
            return SignOut(CookieAuthenticationDefaults.AuthenticationScheme,
                OpenIdConnectDefaults.AuthenticationScheme);
        }
    
        public void OnGet()
        {
            Note = System.IO.File.Exists(NotePath)
                ? System.IO.File.ReadAllText(NotePath)
                : "";
        }
    
        public IActionResult OnPost(string? content)
        {
            System.IO.File.WriteAllText(NotePath, content ?? "");
            return RedirectToPage();
        }
    }
    ```
    
    The `[Authorize]` attribute sends users who aren't logged in to the login page. `OnPostLogout` ends both the app's cookie session and the FusionAuth session.
    
7.  Replace the contents of `Pages/Index.cshtml` with the following code, which adds a Logout button:
    
    ```razor
    @page
    @model Notes.Pages.IndexModel
    @{
        Layout = null;
    }
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Notes</title>
    </head>
    <body>
        <h1>Notes</h1>
        <form method="post" asp-page="/Index">
            <label for="content">Your note</label><br>
            <textarea id="content" name="content" rows="8" cols="40">@Model.Note</textarea><br>
            <button type="submit">Save Changes</button>
        </form>
        <form method="post" asp-page="/Index" asp-page-handler="Logout">
            <button type="submit">Logout</button>
        </form>
    </body>
    </html>
    ```
    
8.  Run the app, which now uses FusionAuth login:
    
    ```shell-session
    $ dotnet run --urls http://localhost:3000
    ```
    
9.  Open the app at [http://localhost:3000](http://localhost:3000) and click Log in with FusionAuth .
    
10.  Log in with the following credentials:
     
     *   username: `richard@example.com`
     *   password: `password`
11.  Edit and save the note in the authenticated .NET app.
     
12.  Click Logout . FusionAuth ends your session and sends you back to the login page.
     
13.  Press **Ctrl+C** on your keyboard to stop the app.
     

## Add Independent Notes for Each User

To see a more realistic example of FusionAuth usage, we can improve the app even more, so every user gets a unique note to edit. To accomplish this, we'll use FusionAuth's user data:

1.  Open the FusionAuth Admin UI at [http://localhost:9011/admin](http://localhost:9011/admin).
    
2.  Log in with the following credentials:
    
    *   username: `admin@example.com`
    *   password: `password`
3.  Navigate to Applications -> QuickStart App -> Edit -> Registration .
    
    *   Under **Self-service registration**, check that **Registration mode** is set to **Create registration**. The QuickStart configuration has already turned on self-service registration.
    *   In the **Registration field** list, turn on the **Enabled** and **Required** switches for the following rows:
        *   **Birthdate**
        *   **First name**
        *   **Last name**
4.  Click Save in the top right of the page to save your changes to self-service registration.
    
5.  Navigate to Users -> Richard Hendricks -> Manage .
    
6.  In the Source tab, look for the `firstName` and `lastName` fields. That's what we'll use to personalize the UI for each user. We'll use the user's `id` field to generate a unique name for each user's note.
    
7.  Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our .NET app.
    
8.  Replace the contents of `Program.cs` with the following code, which adds the `profile` scope so the ID token includes the user's first and last name:
    
    ```csharp
    using Microsoft.AspNetCore.Authentication;
    using Microsoft.AspNetCore.Authentication.Cookies;
    using Microsoft.AspNetCore.Authentication.OpenIdConnect;
    using Microsoft.IdentityModel.Protocols.OpenIdConnect;
    
    var builder = WebApplication.CreateBuilder(args);
    var fusionAuth = builder.Configuration.GetSection("FusionAuth");
    
    builder.Services.AddRazorPages();
    builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options => options.LoginPath = "/login")
        .AddOpenIdConnect(options =>
        {
            options.Authority = fusionAuth["Authority"];
            options.ClientId = fusionAuth["ClientId"];
            options.ClientSecret = fusionAuth["ClientSecret"];
            options.ResponseType = OpenIdConnectResponseType.Code;
            options.UsePkce = true;
            options.RequireHttpsMetadata = !builder.Environment.IsDevelopment();
            options.CallbackPath = "/oauth-callback";
            options.MapInboundClaims = false;
            options.Scope.Clear();
            options.Scope.Add("openid");
            options.Scope.Add("profile");
            options.SaveTokens = true;
            options.Events.OnRedirectToIdentityProviderForSignOut = context =>
            {
                context.ProtocolMessage.PostLogoutRedirectUri = "http://localhost:3000/login";
                return Task.CompletedTask;
            };
        });
    
    var app = builder.Build();
    app.UseAuthentication();
    app.UseAuthorization();
    app.MapRazorPages();
    app.MapGet("/login/start", () => Results.Challenge(
        new AuthenticationProperties { RedirectUri = "/" },
        [OpenIdConnectDefaults.AuthenticationScheme]));
    app.Run();
    ```
    
9.  Replace the contents of `Pages/Index.cshtml.cs` with the following code, which reads the user's name (first and last) and Id from the ID token, and stores each user's note in a separate file:
    
    ```csharp
    using Microsoft.AspNetCore.Authentication.Cookies;
    using Microsoft.AspNetCore.Authentication.OpenIdConnect;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    
    namespace Notes.Pages;
    
    [Authorize]
    public class IndexModel : PageModel
    {
        public string Note { get; private set; } = "";
    
        public string DisplayName
        {
            get
            {
                var firstName = User.FindFirst("given_name")?.Value;
                var lastName = User.FindFirst("family_name")?.Value;
                var name = $"{firstName} {lastName}".Trim();
                return name.Length == 0 ? "writer" : name;
            }
        }
    
        private string NotePath
        {
            get
            {
                var userId = Guid.Parse(User.FindFirst("sub")!.Value);
                return Path.Combine("user_data", $"note-{userId}.txt");
            }
        }
    
        public IActionResult OnPostLogout()
        {
            return SignOut(CookieAuthenticationDefaults.AuthenticationScheme,
                OpenIdConnectDefaults.AuthenticationScheme);
        }
    
        public void OnGet()
        {
            Note = System.IO.File.Exists(NotePath)
                ? System.IO.File.ReadAllText(NotePath)
                : $"Write a note, {DisplayName}.";
        }
    
        public IActionResult OnPost(string? content)
        {
            Directory.CreateDirectory("user_data");
            System.IO.File.WriteAllText(NotePath, content ?? "");
            return RedirectToPage();
        }
    }
    ```
    
    The handler validated the ID token at login and stored its claims in the cookie session, so the page reads `given_name`, `family_name`, and `sub` from `User` without a separate JWT library.
    
10.  Replace the contents of `Pages/Index.cshtml` with the following code, which greets the user by name:
     
     ```razor
     @page
     @model Notes.Pages.IndexModel
     @{
         Layout = null;
     }
     <!DOCTYPE html>
     <html lang="en">
     <head>
         <meta charset="utf-8">
         <title>Notes</title>
     </head>
     <body>
         <h1>Welcome, @Model.DisplayName</h1>
         <form method="post" asp-page="/Index">
             <label for="content">Your note</label><br>
             <textarea id="content" name="content" rows="8" cols="40">@Model.Note</textarea><br>
             <button type="submit">Save Changes</button>
         </form>
         <form method="post" asp-page="/Index" asp-page-handler="Logout">
             <button type="submit">Logout</button>
         </form>
     </body>
     </html>
     ```
     
11.  Run the app:
     
     ```shell-session
     $ dotnet run --urls http://localhost:3000
     ```
     
12.  Open the app at [http://localhost:3000](http://localhost:3000) and click Log in with FusionAuth .
     
13.  Log in with the following credentials:
     
     *   username: `richard@example.com`
     *   password: `password`
14.  In a separate private or incognito window, open the app at [http://localhost:3000](http://localhost:3000) and click Log in with FusionAuth .
     
15.  Click Create an account and create an account using your personal email address, name, and birthdate.
     
16.  Edit and save your own note. Your name appears at the top of the page and in the default note text.
     

Your .NET app now provides unique notes for each user. Each user can independently edit and save their note. To see all of the notes, look for `note-<id>.txt` files in the `user_data` directory. To identify which note corresponds to which user, compare the `id` in the file name with the `id` field in the user's Source tab.

## Summary

In this QuickStart, FusionAuth handled login for your .NET app:

*   The ASP.NET Core OpenID Connect handler sent users to the FusionAuth login page and exchanged the authorization code for tokens, so the app never saw their passwords.
*   The `[Authorize]` attribute kept logged-out users away from the notes page.
*   The ID token gave the app each user's unique Id and name. The app used the Id to keep each note separate and the name to greet the user.
*   FusionAuth's self-service registration let new users create their own accounts, with no sign-up code in the app.

## Next Steps

This was a quick introduction to using FusionAuth for user authentication. To learn more about integrating FusionAuth with your product, see [Get Started](https://fusionauth.io/docs/get-started.md).

FusionAuth has many features (including [Social Login](https://fusionauth.io/docs/authentication/identity-providers.md#social-identity-providers), [Single Sign-On](https://fusionauth.io/docs/authentication/sessions/enable-sso.md), [Passkeys](https://fusionauth.io/docs/authentication/passkeys/configure.md), [Multi-factor Authentication](https://fusionauth.io/docs/authentication/multi-factor-authentication.md)), most of which are free. This example app is a great starting point for learning about FusionAuth features.
---

## Other pages in Web

> For the full index of this section, see [Quickstarts](https://fusionauth.io/docs/llms-quickstarts.txt).

- [FusionAuth QuickStart for Python Django](https://fusionauth.io/docs/quickstarts/web/django.md): Integrate FusionAuth with an example Python Django website.
- [FusionAuth QuickStart for Express](https://fusionauth.io/docs/quickstarts/web/express.md): Integrate FusionAuth with an example Express website.
- [FusionAuth QuickStart for Python Flask](https://fusionauth.io/docs/quickstarts/web/flask.md): Integrate FusionAuth with an example Python Flask website.
- [Web](https://fusionauth.io/docs/quickstarts/web.md): Explore step-by-step web application QuickStart guides from FusionAuth to seamlessly integrate authentication into your application.
- [FusionAuth QuickStart for Next.js](https://fusionauth.io/docs/quickstarts/web/nextjs.md): Integrate FusionAuth with an example Next.js website.
- [FusionAuth QuickStart for Nuxt](https://fusionauth.io/docs/quickstarts/web/nuxt.md): Integrate FusionAuth with an example Nuxt website.
- [FusionAuth QuickStart for Golang](https://fusionauth.io/docs/quickstarts/web/quickstart-golang-web.md): QuickStart integration of a Golang web application with FusionAuth using the CoreOS OIDC library.
- [FusionAuth QuickStart for Spring Boot With Thymeleaf](https://fusionauth.io/docs/quickstarts/web/quickstart-java-springboot-web.md): QuickStart integration of a Spring Boot web application using Thymeleaf with FusionAuth.
- [FusionAuth QuickStart for Remix](https://fusionauth.io/docs/quickstarts/web/quickstart-javascript-remix-web.md): QuickStart integration of Javascript Remix web application with FusionAuth.
- [FusionAuth QuickStart for Drupal](https://fusionauth.io/docs/quickstarts/web/quickstart-php-drupal-web.md): QuickStart integration of Drupal web application with FusionAuth.
- [FusionAuth QuickStart for Laravel](https://fusionauth.io/docs/quickstarts/web/quickstart-php-laravel-web.md): QuickStart integration of PHP Laravel web application with FusionAuth.
- [FusionAuth QuickStart for PHP](https://fusionauth.io/docs/quickstarts/web/quickstart-php-web.md): QuickStart integration of PHP web application with FusionAuth.
- [FusionAuth QuickStart for Ruby on Rails](https://fusionauth.io/docs/quickstarts/web/quickstart-ruby-rails-web.md): QuickStart integration of Ruby on Rails web application with FusionAuth.
- [FusionAuth QuickStart for Rust with Actix](https://fusionauth.io/docs/quickstarts/web/quickstart-rust-actix-web.md): QuickStart integration of a Rust Actix web application with FusionAuth.
- [FusionAuth QuickStart for WordPress](https://fusionauth.io/docs/quickstarts/web/quickstart-wordpress-web.md): QuickStart integration of WordPress application with FusionAuth.
