Build ASP.NET Core authentication with Logto

Learn how to build a user authentication flow with ASP.NET Core by integrating Logto SDK.
Gao
GaoFounder
September 03, 20236 min read
Build ASP.NET Core authentication with Logto

Introduction

  • Logto is a modern Auth0 alternative for building customer identity infrastructure with minimal effort. It supports various sign-in methods, including username, email, phone number, and popular social sign-ins like Google and GitHub.
  • ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern, cloud-based, Internet-connected applications.

In this tutorial, we will show you how to build a user authentication flow with ASP.NET Core by integrating Logto SDK. The tutorial uses C# as the programming language.

Prerequisites

Before you begin, ensure you have the following:

  • A Logto account. If you don't have one, you can sign up for free.
  • A .NET development environment and an ASP.NET Core project. If you don't have one, you can install .NET and follow the ASP.NET tutorials to set up your project.

Create a Logto application

To get started, create a Logto application with the "Traditional web" type. Follow these steps to create a Logto application:

  1. Sign in to the Logto Console.
  2. In the left navigation bar, click on Applications.
  3. Click on Create application.
  4. In the opened page, find the "Traditional web app" section and locate the "ASP.NET Core" card.
  5. Click on Start building, and input the name of your application.
  6. Click on Create.

Then you should see an interactive tutorial that guides you through the process of integrating Logto SDK with your ASP.NET Core application. The following content can be a reference for future use.

Integrate with Logto SDK

Installation

dotnet add package Logto.AspNetCore.Authentication

Note the minimum supported version of ASP.NET Core is 6.0.

Add Logto authentication middleware

Open Startup.cs (or Program.cs) and add the following code to register Logto authentication middleware:

using Logto.AspNetCore.Authentication;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddLogtoAuthentication(options =>
{
  options.Endpoint = builder.Configuration["Logto:Endpoint"]!;
  options.AppId = builder.Configuration["Logto:AppId"]!;
  options.AppSecret = builder.Configuration["Logto:AppSecret"];
});

app.UseAuthentication();

The AddLogtoAuthentication method will do the following things:

  • Set the default authentication scheme to LogtoDefaults.CookieScheme.
  • Set the default challenge scheme to LogtoDefaults.AuthenticationScheme.
  • Set the default sign-out scheme to LogtoDefaults.AuthenticationScheme.
  • Add cookie and OpenID Connect authentication handlers to the authentication scheme.

Sign-in

Add the following URI to the Redirect URIs list in the Logto application details page:

http://<your-web-app-uri>/Callback

To sign-in with Logto, you can use the ChallengeAsync method:

await HttpContext.ChallengeAsync(new AuthenticationProperties
{
  RedirectUri = "/"
});

The ChallengeAsync method will redirect the user to the Logto sign-in page.

The RedirectUri property is used to redirect the user back to your web application after authentication. Note it is different from the redirect URI you configured in the Logto application details page:

  1. The redirect URI in the Logto application details page is the URI that Logto will redirect the user back to after the user has signed in.
  2. The RedirectUri property is the URI that will be redirected to after necessary actions have been taken in the Logto authentication middleware.

The order of the actions is 1 -> 2. For clarity, let's call the redirect URI in the Logto application details page the Logto redirect URI and the RedirectUri property the application redirect URI.

The Logto redirect URI has a default value of /Callback, which you can leave it as is if there's no special requirement. If you want to change it, you can set the CallbackPath property for LogtoOptions:

builder.Services.AddLogtoAuthentication(options =>
{
  options.CallbackPath = "/SomeOtherCallbackPath";
});

Remember to update the value in the Logto application details page accordingly.

No need to set the application redirect URI in the Logto application details page.

Sign-out

Add the following URI to the Post sign-out redirect URIs list in the Logto application details page:

http://<your-web-app-uri>/SignedOutCallback

To sign-out with Logto, you can use the SignOutAsync method:

await HttpContext.SignOutAsync(new AuthenticationProperties
{
  RedirectUri = "/"
});

The SignOutAsync method will clear the authentication cookie and redirect the user to the Logto sign-out page.

The RedirectUri property is used to redirect the user back to your web application after sign-out. Note it is different from the post sign-out redirect URI you configured in the Logto application details page:

  1. The post sign-out redirect URI in the Logto application details page is the URI that Logto will redirect the user back to after the user has signed out.
  2. The RedirectUri property is the URI that will be redirected to after necessary actions have been taken in the Logto authentication middleware.

The order of the actions is 1 -> 2. For clarity, let's call the post sign-out redirect URI in the Logto application details page the Logto post sign-out redirect URI and the RedirectUri property the application post sign-out redirect URI.

The Logto post sign-out redirect URI has a default value of /SignedOutCallback, which you can leave it as is if there's no special requirement. If you want to change it, you can set the SignedOutCallbackPath property for LogtoOptions:

builder.Services.AddLogtoAuthentication(options =>
{
  options.SignedOutCallbackPath = "/SomeOtherSignedOutCallbackPath";
});

Remember to update the value in the Logto application details page accordingly.

No need to set the application post sign-out redirect URI in the Logto application details page.

Implement sign-in/sign-out buttons (Razor Pages)

First, add the handler methods to your PageModel, for example:

public class IndexModel : PageModel
{
  public async Task OnPostSignInAsync()
  {
    await HttpContext.ChallengeAsync(new AuthenticationProperties
    {
      RedirectUri = "/"
    });
  }

  public async Task OnPostSignOutAsync()
  {
    await HttpContext.SignOutAsync(new AuthenticationProperties
    {
      RedirectUri = "/"
    });
  }
}

Then, add the buttons to your Razor page (html):

<p>Is authenticated: @User.Identity?.IsAuthenticated</p>
<form method="post">
  @if (User.Identity?.IsAuthenticated == true)
  {
    <button type="submit" asp-page-handler="SignOut">Sign out</button>
  } else {
    <button type="submit" asp-page-handler="SignIn">Sign in</button>
  }
</form>

It will show the "Sign in" button if the user is not authenticated, and show the "Sign out" button if the user is authenticated.

Checkpoint: Run the web application

Now you can run the web application and try to sign-in/sign-out with Logto:

  1. Open the web application in your browser, you should see "Is authenticated: False" and the "Sign in" button.
  2. Click the "Sign in" button, and you should be redirected to the Logto sign-in page.
  3. After you have signed in, you should be redirected back to the web application, and you should see "Is authenticated: True" and the "Sign out" button.
  4. Click the "Sign out" button, and you should be redirected to the Logto sign-out page, and then redirected back to the web application.

If you encounter any issues during the integration, please don't hesitate to contact us via email at [email protected] or join our Discord server!

Further readings