joydip_kanjilal
Contributor

How to implement identity authentication in minimal APIs in ASP.NET Core

how-to
May 23, 20246 mins
C#Development Libraries and FrameworksMicrosoft .NET

Take advantage of improved identity management in ASP.NET Core to implement identity-based authentication for minimal APIs quickly, easily, and with less code.

twin dogs black and white with pink and blue kerchiefs neck scarfs
Credit: Moriah Maddux / Shutterstock

Minimal APIs in ASP.NET Core allow us to build lightweight APIs with minimal dependencies. However, often we will still need authentication and authorization in our minimal APIs. There are several ways to achieve this in ASP.NET Core including basic authentication, token-based authentication, and identity-based authentication.

We discussed implementing basic authentication in minimal APIs here, and JWT token-based authentication in minimal APIs here. In this article we’ll examine how we can implement identity-based authentication for minimal APIs in ASP.NET Core.

To use the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.

Create an ASP.NET Core Web API project in Visual Studio 2022

To create an ASP.NET Core Web API project in Visual Studio 2022, follow the steps outlined below.

  1. Launch the Visual Studio 2022 IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
  6. Click Next.
  7. In the “Additional Information” window shown next, select “.NET 8.0 (Long Term Support)” as the framework version and uncheck the check box that says “Use controllers,” as we’ll be using minimal APIs in this project.
  8. Elsewhere in the “Additional Information” window, leave the “Authentication Type” set to “None” (the default) and make sure the check boxes “Enable Open API Support,” “Configure for HTTPS,” and “Enable Docker” remain unchecked. We won’t be using any of those features here.
  9. Click Create.

We’ll use this ASP.NET Core Web API project to work with the code examples given in the sections below.

Identity management in ASP.NET Core

ASP.NET Core includes a powerful feature known as identity management that has been enhanced in .NET 8. The built-in Identity framework in ASP.NET Core provides the necessary middleware to implement authentication, user management, and role-based authorization, thereby making it simpler to implement robust and secure authentication mechanisms in your application.

ASP.NET Core’s Identity framework is extensible and customizable with support for the following key features:

  • Authentication and authorization
  • User management
  • Roles management
  • Password hashing
  • Token-based authentication
  • Claims-based authentication

Create a minimal API in ASP.NET Core

In the Web API project we created above, replace the generated code with the following code to create a basic minimal API.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/helloworld", () => "Hello, World!");
app.Run();

When you execute the application, the text “Hello World!” will be displayed in your web browser. We’ll use this endpoint later in this article.

Install NuGet packages

To add support for the built-in Identity framework in ASP.NET Core, select the project in the Solution Explorer window, then right-click and select “Manage NuGet Packages.” In the NuGet Package Manager window, search for the Microsoft.AspNetCore.Identity.EntityFrameworkCore, Microsoft.EntityFrameworkCore.SqlServer, and Microsoft.EntityFrameworkCore.Design packages and install them.

Alternatively, you can install the packages via the NuGet Package Manager console by entering the commands listed below.

PM> Install-Package Microsoft.AspNetCore.Identity.EntityFrameworkCore
PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer
PM> Install-Package Microsoft.EntityFrameworkCore.Design

Create a new DbContext in EF Core

We’ll be using Entity Framework Core in this example. The DbContext is an integral component of EF Core that represents a connection session with the database. Next, create a custom DbContext class by extending the IdentityDbContext class as shown in the code snippet given below.

public class CustomDbContext(DbContextOptions<CustomDbContext> options)
    : IdentityDbContext<IdentityUser>(options){ } 

You should register the custom DbContext class by including the following line of code in the Program.cs file.

builder.Services.AddDbContext<CustomDbContext>();

Enable authentication and authorization in ASP.NET Core

Authentication is the process of determining who the user is and validating the user’s identity. You can enable authentication in a minimal API in ASP.NET Core by using the AddAuthentication() method as shown in the code snippet given below.

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication();

We use authorization to restrict access to certain resources in an application. You can enable authorization in your minimal API by using the following code.

builder.Services.AddAuthorization();

The AddAuthorization method is used to register authorization services with the services container so that you can define rules for enabling or disabling access to resources of the application if needed.

Configure services and API endpoints in ASP.NET Core

The next thing we need to do is configure the identity and EF Core services and the API endpoints. To do this, include the code listing given below in the Program.cs file.

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
builder.Services.AddDbContext<CustomDbContext>();
builder.Services.AddAuthorization();
builder.Services.AddIdentityApiEndpoints()
    .AddEntityFrameworkStores();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.MapIdentityApi();

The AddIdentityApiEndpoints() method in the preceding code snippet adds the necessary controllers and services for authentication and authorization (login, logout, registration, etc.). Note that this is a new method (introduced in .NET 8) used to configure Identity integration in an application. The AddIdentityApiEndpoints() method accepts an instance of type IdentityUser as a parameter, which is used to specify the type of user.

You can use the following piece of code to add authorization for the /helloworld endpoint.

app.MapGet("/helloworld", () => "Hello World!")
.RequireAuthorization();

Complete source of the Program.cs file

The complete source code of the Program.cs file is given below for your reference.

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddDbContext<CustomDbContext>();
builder.Services.AddAuthorization();
builder.Services.AddIdentityApiEndpoints()
    .AddEntityFrameworkStores();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.MapIdentityApi();
// Configure the HTTP request pipeline.
app.MapGet("/helloworld", () => "Hello World!")
.RequireAuthorization();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
});
app.Run();
public class CustomDbContext(DbContextOptions options)
    : IdentityDbContext(options)
{
    protected override void OnConfiguring(DbContextOptionsBuilder options) =>
    options.UseSqlite("DataSource = DemoDb; Cache=Shared");
}

The integrated identity management feature in ASP.NET Core is both powerful and easy to use. The improvements in .NET 8 have made Identity even more robust and flexible with an improved Identity API, which enables you to implement identity-based  authentication and authorization more easily and efficiently with less code.

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author