Authgear
Start BuildingHomePortalCommunity
  • Authgear Overview
  • Get Started
    • Start Building
    • 5-Minute Guide
    • Single-Page App
      • JavaScript (Web)
      • React
      • Angular
      • Vue
    • Native/Mobile App
      • iOS SDK
      • Android SDK
        • Android Kotlin coroutine support
        • Android OKHttp Interceptor Extension (Optional)
      • Flutter SDK
      • React Native SDK
      • Ionic SDK
      • Xamarin SDK
      • Using Authgear without SDK (Client side)
    • Regular Web App
      • Express
      • Next.js
      • Python Flask App
      • Java Spring Boot
      • ASP.NET Core MVC
      • Laravel
      • PHP
    • Backend/API Integration
      • Validate JWT in your application server
      • Forward Authentication to Authgear Resolver Endpoint
    • AI Coding tools
      • Cursor/Windsurf
  • How-To Guides
    • Authenticate
      • Add Passkeys Login
      • Add WhatsApp OTP Login
      • Add Email Magic Link Login
      • Add Biometric Login
      • Add Anonymous Users
      • Add authentication to any web page
      • Enable Two-Factor Authentication (2FA)
      • How to Use the OAuth 2.0 State Parameter
      • Reauthentication
      • How to Use Social/Enterprise Login Providers Without AuthUI
      • Passwordless Login for Apple App Store Review
      • Setup local development environment for Cookie-based authentication
      • Forgot/Reset Password settings
      • Phone number validation
      • Set Password Expiry
    • Single Sign-on
      • App2App Login
      • Pre-authenticated URLs
      • SSO between Mobile Apps / Websites
      • Force Authgear to Show Login Page
      • Single Sign-On with OIDC
      • Single Sign-On with SAML
        • Use Authgear as SAML Identity Provider for Salesforce
        • Use Authgear as SAML Identity Provider for Dropbox
        • SAML Attribute Mapping
    • Social Login / Enterprise Login Providers
      • Social Login Providers
        • Connect Apps to Apple
        • Connect Apps to Google
        • Connect Apps to Facebook
        • Connect Apps to GitHub
        • Connect Apps to LinkedIn
        • Connect Apps to WeChat
      • Enterprise Login Providers
        • Connect Apps to Azure Active Directory
        • Connect Apps to Microsoft AD FS
        • Connect Apps to Azure AD B2C
      • Force Social/Enterprise Login Providers to Show Login Screen
    • Built-in UI
      • Branding in Auth UI
      • User Settings
      • Privacy Policy & Terms of Service Links
      • Customer Support Link
      • Custom Text
    • Custom UI
      • Authentication Flow API
      • Implement Authentication Flow API using Express
      • Implement Authentication Flow API using PHP
      • Add Custom Login/Signup UI to Native Apps
      • Manually Link OAuth Provider using Account Management API
      • Implement a custom account recovery UI using Authentication Flow API
    • Integrate
      • Add custom fields to a JWT Access Token
      • User Analytics by Google Tag Manager
      • Track User Before and After Signup
      • Custom domain
      • Custom Email Provider
      • Custom SMS Provider
        • Twilio
        • Webhook/Custom Script
    • Monitor
      • Audit Log For Users Activities
      • Audit Log for Admin API and Portal
      • Analytics
    • User Management
      • Account Deletion
      • Import Users using User Import API
      • Export Users using the User Export API
      • Manage Users Roles and Groups
      • How to Handle Password While Creating Accounts for Users
    • User Profiles
      • What is User Profile
      • Access User Profiles
      • Update User Profiles
      • Profile Custom Attributes
      • Update user profile on sign-up using Hooks
    • Events and Hooks
      • Event List
      • Webhooks
      • JavaScript / TypeScript Hooks
      • Only Allow Signups from Inside the Corporate Network using Hooks
    • Mobile Apps
      • Use SDK to make authorized API calls to backend
      • Force authentication on app launch
      • Customize the Login Pop-up / Disable the login alert box
    • Languages and Localization
    • Custom Email and SMS Templates
    • Directly accessing Authgear Endpoint
    • Migration
      • Bulk migration
      • Rolling migration
      • Zero-downtime migration
    • Troubleshoot
      • How to Fix SubtleCrypto: digest() undefined Error in Authgear SDK
      • How to Fix CORS Error
  • Concepts
    • Identity Fundamentals
    • Authgear use cases
    • User, Identity and Authenticator
  • Security
    • Brute-force Protection
    • Bot Protection
    • Non-HTTP scheme redirect URI
    • Password Strength
  • Reference
    • APIs
      • Admin API
        • Authentication and Security
        • API Schema
        • Admin API Examples
        • Using global node IDs
        • Retrieving users using Admin API
        • User Management Examples
          • Search for users
          • Update user's standard attributes
          • Update user's picture
          • Generate OTP code
      • Authentication Flow API
      • OAuth 2.0 and OpenID Connect (OIDC)
        • UserInfo
        • Supported Scopes
      • User Import API
      • User Export API
    • Tokens
      • JWT Access Token
      • Refresh Token
    • Glossary
    • Billing FAQ
    • Rate Limits
      • Account Lockout
  • Client App SDKs
    • Javascript SDK Reference
    • iOS SDK Reference
    • Android SDK Reference
    • Flutter SDK Reference
    • Xamarin SDK Reference
  • Deploy on your Cloud
    • Running locally with Docker
    • Deploy with Helm chart
    • Authenticating HTTP request with Nginx
    • Configurations
      • Environment Variables
      • authgear.yaml
      • authgear.secrets.yaml
    • Reference Architecture Diagrams
      • Google Cloud Reference Architecture
      • Azure Reference Architecture
      • AWS Reference Architecture
      • Throughput Scaling Reference
Powered by GitBook
On this page
  • Learning objectives
  • Add authentication to ASP.NET Core App
  • Prerequisites
  • Part 1: Configure Authgear
  • Part 2: Configure ASP.NET Core application to use Authgear

Was this helpful?

Edit on GitHub
  1. Get Started
  2. Regular Web App

ASP.NET Core MVC

Add authentication for ASP.NET app with Authgear

PreviousJava Spring BootNextLaravel

Last updated 1 year ago

Was this helpful?

In this guide, you will learn how to add authentication features with by implementing an flow, then retrieving OAuth tokens, to call APIs. View on GitHub.

Learning objectives

You will learn the following throughout the article:

  • How to add user login, sign-up, and logout to Core Applications.

  • How to use the Core Authorization Middleware to protect Core application routes.

Add authentication to Core App

Prerequisites

Before you get started, you will need the following:

  • A free Authgear account. if you don't have one already.

  • downloaded and installed on your machine. You can also use and to automatically detect the .NET version.

Part 1: Configure Authgear

To use Authgear services, you’ll need to have an application set up in the Authgear . The Authgear application is where you will configure how you want to authenticate and manage your users.

Step 1: Configure an application

Use the interactive selector to create a new Authgear OIDC Client application or select an existing application that represents the project you want to integrate with.

Step 2: Configure Redirect URI

Step 3: Enable Access Token

Also, enable Issue JWT as an access token option under the Access Token section of the app configuration:

Step 4: Choose a Login method

After you create the Authgear app, you choose how users need to authenticate on the login page. From the Authentication tab, navigate to Login Methods, you can choose a login method from various options including, by email, mobile, or social, just using a username or the custom method you specify. For this demo, we choose the Email+Passwordless approach where our users are asked to register an account and log in by using their emails. They will receive a One-time password (OTP) to their emails and verify the code to use the app.

Step 1: Install dependencies

Install-Package Microsoft.AspNetCore.Authentication.OpenIdConnect

Step 2: Install and configure OpenID Connect Middleware

public class Startup
 {

     public IWebHostEnvironment Environment { get; }
     public IConfiguration Configuration { get; }

     public Startup(IWebHostEnvironment environment, IConfiguration config)
     {
         Environment = environment;
         Configuration = config;
     }

     // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
     public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
     {
         app.UseRouting();
         app.UseAuthentication();
         app.UseAuthorization();
         app.UseEndpoints(endpoints =>
         {
             endpoints.MapRazorPages();
         });
     }

     public void ConfigureServices(IServiceCollection services)
     {
         // Prevent WS-Federation claim names being written to tokens
         JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

         services.AddAuthentication(options =>
         {
             options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
             options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
         })
         .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
         {
             // Use the strongest setting in production, which also enables HTTP on developer workstations
             options.Cookie.SameSite = SameSiteMode.Strict;
         })
         .AddOpenIdConnect(options =>
         {

             // Use the same settings for temporary cookies
             options.NonceCookie.SameSite = SameSiteMode.Strict;
             options.CorrelationCookie.SameSite = SameSiteMode.Strict;

             // Set the main OpenID Connect settings
             options.Authority = Configuration.GetValue<string>("OpenIdConnect:Issuer");
             options.ClientId = Configuration.GetValue<string>("OpenIdConnect:ClientId");
             options.ClientSecret = Configuration.GetValue<string>("OpenIdConnect:ClientSecret");
             options.ResponseType = OpenIdConnectResponseType.Code;
             options.ResponseMode = OpenIdConnectResponseMode.Query;
             string scopeString = Configuration.GetValue<string>("OpenIDConnect:Scope");
             options.Scope.Clear();
             scopeString.Split(" ", StringSplitOptions.TrimEntries).ToList().ForEach(scope =>
             {
                 options.Scope.Add(scope);
             });

             // If required, override the issuer and audience used to validate ID tokens
             options.TokenValidationParameters = new TokenValidationParameters
             {
                 ValidIssuer = options.Authority,
                 ValidAudience = options.ClientId
             };

             // This example gets user information for display from the user info endpoint
             options.GetClaimsFromUserInfoEndpoint = true;

             // Handle the post logout redirect URI
             options.Events.OnRedirectToIdentityProviderForSignOut = (context) =>
             {
                 context.ProtocolMessage.PostLogoutRedirectUri = Configuration.GetValue<string>("OpenIdConnect:PostLogoutRedirectUri");
                 return Task.CompletedTask;
             };

             // Save tokens issued to encrypted cookies
             options.SaveTokens = true;

             // Set this in developer setups if the OpenID Provider uses plain HTTP
             options.RequireHttpsMetadata = false;
         });

         services.AddAuthorization();
         services.AddRazorPages();

         // Add this app's types to dependency injection
         services.AddSingleton<TokenClient>();
     }
 }

Step 3: Add Protected resource

Assume that there is a protected resource like a Razor page Protected.cshtml that is used to represent views:

@page "/protected"
@model ProtectedModel

@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers

<style type="text/css">
button
{
  width: 200px;
}
</style>

<h1>Protected View</h1>

<h3>
    <p>Welcome: @Model.Username</a>
    <p>Current Access Token: @Model.AccessToken</a>
    <p>Current Refresh Token: @Model.RefreshToken</a>
    
    <form method="post">
        <p><button value="RefreshToken" asp-page-handler="RefreshToken">Refresh Token</button></p>
        <p><button value="Logout" asp-page-handler="Logout">Logout</button></p>
    </form>
</h3>

And ProtectedModel.cs class to which Authorize the attribute is applied requires authorization.

[Authorize]
public class ProtectedModel : PageModel
{
    public string Username { get; set; }
    public string AccessToken { get; set; }
    public string RefreshToken { get; set; }

    private readonly TokenClient tokenClient;

    public ProtectedModel(TokenClient tokenClient)
    {
        this.tokenClient = tokenClient;
    }

    public async Task OnGet()
    {
        ClaimsPrincipal user = this.User;
        var givenName = user.FindFirstValue("given_name");
        var familyName = user.FindFirstValue("family_name");
        this.Username = $"{givenName} {familyName}";

        this.AccessToken = await this.tokenClient.GetAccessToken(this.HttpContext);
        this.RefreshToken = await this.tokenClient.GetRefreshToken(this.HttpContext);
    }

    public async Task<IActionResult> OnPostRefreshToken()
    {
        await this.tokenClient.RefreshAccessToken(this.HttpContext);
        this.AccessToken = await this.tokenClient.GetAccessToken(this.HttpContext);
        this.RefreshToken = await this.tokenClient.GetRefreshToken(this.HttpContext);
        return Page();
    }

    public async Task OnPostLogout()
    {
        await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
    }
}

To see protected data, users need to go through the authentication process via Authgear.

If a user has not authenticated yet, Unauthenticated.chtml the page is rendered, an OpenID Connect redirect flow is triggered and the user needs to authenticate through the Authgear login page. See Run the Application section

After successful authentication, you should see the protected page with the following details:

Step 4: Get and Use Refresh Token

As part of the OAuth 2.0 standard, we can use the refresh token returned by the token endpoint to get a new access token. Doing so enables our application to replace an expired access token without requiring the user to repeat the entire login process.

The following code in ProtectedModel.cs is responsible for doing that:

public async Task<IActionResult> OnPostRefreshToken()
{
    await this.tokenClient.RefreshAccessToken(this.HttpContext);
    this.AccessToken = await this.tokenClient.GetAccessToken(this.HttpContext);
    this.RefreshToken = await this.tokenClient.GetRefreshToken(this.HttpContext);
    return Page();
}

Note: You must include offline_access in your OAuth 2.0 scope for the Authgear authorization server to return a refresh token.

Step 5: Logout

The Logout button on the Protected.cshtml page calls the OnPostLogout() method in ProtectedModel.cs. The method will delete the current user session and redirect to Authgear's end session endpoint for the user to complete the logout process.

The code sample below shows the implementation of the OnPostLogout() method:

public async Task OnPostLogout()
    {
        await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
    }

Step 6: Set up and run the application

Start by cloning the project into your local machine:

git clone 

Make the project directory your current working directory:

cd authgear-example-dotnet

Update the following configuration variables in the appsettings.json file with your Authgear app settings values from Part1 such as Issuer, ClientId, ClientSecret, and Authgear endpoint:

{
    "OpenIDConnect": {
        "ClientId": "{your-client-id}",
        "ClientSecret": "{your-client-secret}",
        "Issuer": "{your-authgear-app-endpoint}",
        "Scope": "openid offline_access",
        "PostLogoutRedirectUri": "<http://localhost:5002>",
        "TokenEndpoint": "{your-authgear-app-endpoint}/oauth2/token"
    },
    "Urls": "<http://localhost:5002>",
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    }
}
dotnet build
dotnet run

After you have authenticated, a protected view is rendered. The application receives an Access token that it uses to present user data on the screen, and tokens that could be used in upstream requests to some backend API, to access data on behalf of the user.

Next steps

This guide showed how to quickly implement an end-to-end OpenID Connect flow in .NET with Authgear. Only simple code is needed, after which protected views are secured with built-in UI login pages.

Every application in Authgear is assigned an alphanumeric, unique client ID that your application code will use to call Authgear APIs through the OpenID Connect Client in the .NET app. Note down the Authgear ISSUER (for example, ), CLIENT ID, CLIENT SECRET, and OpenID Token Endpoint () from the output. You will use these values in the next step for the client app config.

A Redirect URI of your application is the URL that Authgear will redirect to after the user has authenticated in order for the OpenID Connect middleware to complete the authentication process. In our case, it will be a home page for our and it will run at.

Set the following redirect URI: If not set, users will not be returned to your application after they log in.

Part 2: Configure Core application to use Authgear

This guide will be used to provide a way for your users to log in to your Core application. The can be found on GitHub. If you are familiar with the steps, you can skip this part and clone the code repository and run the code sample by following the file there.

To integrate Authgear with Core you will use both the Cookie and OpenID Connect (OIDC) authentication handlers. If you are not using a sample project and are integrating Authgear into your own existing project, then please make sure that you add Microsoft.AspNetCore.Authentication.OpenIdConnect packages to your application. Run the following command in your terminal or use your editor to include the NuGet package there:

To enable authentication in your Core application, use the OpenID Connect (OIDC) middleware. Open Startup the class and in the ConfigureServices method, add the authentication services and call the AddAuthentication method. To enable cookie authentication, call the AddCookie method. Next, configure the OIDC authentication handler by adding method AddOpenIdConnect implementation. Configure other parameters, such as Issuer, ClientId, ClientSecret , and Scope. Here, is what looks like Startup.cs after you apply these changes:

Execute the following command to run the Core web application:

You can now visit to access the application. When you click on the "View Protected Data" button, Core takes you to the Authgear’s Login page.

Your users can log in to your application through a page hosted by Authgear, which provides them with a secure, standards-based login experience that you can customize with your own branding and various authentication methods, such as , , , with SMS/WhatsApp, and multi-factor authentication (MFA).

Authgear
OpenID Connect
implementation
ASP.NET
ASP.NET
ASP.NET
ASP.NET
Sign up
.NET 7
Visual Studio
VS code
Dashboard
https://example-auth.authgear.cloud
https://example-auth.authgear.cloud/oauth2/token
ASP.NET
http://localhost:5002
http://localhost:5002/signin-oidc
ASP.NET
ASP.NET
project source code
README.md
ASP.NET
ASP.NET
ASP.NET
http://localhost:5002
ASP.NET
social logins
passwordless
biometrics logins
one-time-password (OTP)