Take advantage of improved identity management in ASP.NET Core to implement identity-based authentication for minimal APIs quickly, easily, and with less code. 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. Launch the Visual Studio 2022 IDE. Click on “Create new project.” In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed. Click Next. 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. Click Next. 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. 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. 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. Related content news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks news Akka distributed computing platform adds Java SDK Akka enables development of applications that are primarily event-driven, deployable on Akka’s serverless platform or on AWS, Azure, or GCP cloud instances. By Paul Krill Nov 18, 2024 2 mins Java Scala Serverless Computing news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks how-to How to use DispatchProxy for AOP in .NET Core Take advantage of the DispatchProxy class in C# to implement aspect-oriented programming by creating proxies that dynamically intercept method calls. By Joydip Kanjilal Nov 14, 2024 7 mins Microsoft .NET C# Development Libraries and Frameworks Resources Videos