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

By Joydip Kanjilal

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.

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:

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.EntityFrameworkCorePM> Install-Package Microsoft.EntityFrameworkCore.SqlServerPM> 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<IdentityUser>() .AddEntityFrameworkStores<CustomDbContext>();builder.Services.AddEndpointsApiExplorer();builder.Services.AddSwaggerGen();var app = builder.Build();app.MapIdentityApi<IdentityUser>();

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<IdentityUser>() .AddEntityFrameworkStores<CustomDbContext>();builder.Services.AddEndpointsApiExplorer();builder.Services.AddSwaggerGen();var app = builder.Build();app.MapIdentityApi<IdentityUser>();// 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<CustomDbContext> options) : IdentityDbContext<IdentityUser>(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.

© Info World