Monday, April 28, 2025

Learn how to implement identification authentication in minimal APIs in ASP.NET Core


Minimal APIs in ASP.NET Core enable us to construct light-weight APIs with minimal dependencies. Nevertheless, typically we are going to nonetheless want authentication and authorization in our minimal APIs. There are a number of methods to attain this in ASP.NET Core together with primary authentication, token-based authentication, and identity-based authentication.

We mentioned implementing primary authentication in minimal APIs right here, and JWT token-based authentication in minimal APIs right here. On this article we’ll look at how we are able to implement identity-based authentication for minimal APIs in ASP.NET Core.

To make use of the code examples supplied on this article, it’s best to have Visible Studio 2022 put in in your system. Should you don’t have already got a replica, you may obtain Visible Studio 2022 right here.

Create an ASP.NET Core Net API mission in Visible Studio 2022

To create an ASP.NET Core Net API mission in Visible Studio 2022, observe the steps outlined beneath.

  1. Launch the Visible Studio 2022 IDE.
  2. Click on on “Create new mission.”
  3. Within the “Create new mission” window, choose “ASP.NET Core Net API” from the checklist of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new mission” window, specify the title and placement for the brand new mission. Optionally test the “Place resolution and mission in the identical listing” test field, relying in your preferences.
  6. Click on Subsequent.
  7. Within the “Further Data” window proven subsequent, choose “.NET 8.0 (Lengthy Time period Assist)” because the framework model and uncheck the test field that claims “Use controllers,” as we’ll be utilizing minimal APIs on this mission.
  8. Elsewhere within the “Further Data” window, depart the “Authentication Kind” set to “None” (the default) and ensure the test bins “Allow Open API Assist,” “Configure for HTTPS,” and “Allow Docker” stay unchecked. We received’t be utilizing any of these options right here.
  9. Click on Create.

We’ll use this ASP.NET Core Net API mission to work with the code examples given within the sections beneath.

Id administration in ASP.NET Core

ASP.NET Core features a highly effective function referred to as identification administration that has been enhanced in .NET 8. The built-in Id framework in ASP.NET Core supplies the mandatory middleware to implement authentication, consumer administration, and role-based authorization, thereby making it less complicated to implement strong and safe authentication mechanisms in your software.

ASP.NET Core’s Id framework is extensible and customizable with assist for the next key options:

  • Authentication and authorization
  • Person administration
  • Roles administration
  • Password hashing
  • Token-based authentication
  • Claims-based authentication

Create a minimal API in ASP.NET Core

Within the Net API mission we created above, change the generated code with the next code to create a primary minimal API.

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

If you execute the appliance, the textual content “Good day World!” will likely be displayed in your internet browser. We’ll use this endpoint later on this article.

Set up NuGet packages

So as to add assist for the built-in Id framework in ASP.NET Core, choose the mission within the Resolution Explorer window, then right-click and choose “Handle NuGet Packages.” Within the NuGet Bundle Supervisor window, seek for the Microsoft.AspNetCore.Id.EntityFrameworkCore, Microsoft.EntityFrameworkCore.SqlServer, and Microsoft.EntityFrameworkCore.Design packages and set up them.

Alternatively, you may set up the packages by way of the NuGet Bundle Supervisor console by coming into the instructions listed beneath.

PM> Set up-Bundle Microsoft.AspNetCore.Id.EntityFrameworkCore
PM> Set up-Bundle Microsoft.EntityFrameworkCore.SqlServer
PM> Set up-Bundle Microsoft.EntityFrameworkCore.Design

Create a brand new DbContext in EF Core

We’ll be utilizing Entity Framework Core on this instance. The DbContext is an integral element of EF Core that represents a connection session with the database. Subsequent, create a customized DbContext class by extending the IdentityDbContext class as proven within the code snippet given beneath.

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

It’s best to register the customized DbContext class by together with the next line of code within the Program.cs file.

builder.Providers.AddDbContext<CustomDbContext>();

Allow authentication and authorization in ASP.NET Core

Authentication is the method of figuring out who the consumer is and validating the consumer’s identification. You’ll be able to allow authentication in a minimal API in ASP.NET Core through the use of the AddAuthentication() methodology as proven within the code snippet given beneath.

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

We use authorization to limit entry to sure sources in an software. You’ll be able to allow authorization in your minimal API through the use of the next code.

builder.Providers.AddAuthorization();

The AddAuthorization methodology is used to register authorization companies with the companies container as a way to outline guidelines for enabling or disabling entry to sources of the appliance if wanted.

Configure companies and API endpoints in ASP.NET Core

The following factor we have to do is configure the identification and EF Core companies and the API endpoints. To do that, embrace the code itemizing given beneath within the Program.cs file.

utilizing Microsoft.AspNetCore.Id;
utilizing Microsoft.AspNetCore.Id.EntityFrameworkCore;
utilizing Microsoft.EntityFrameworkCore;
builder.Providers.AddDbContext<CustomDbContext>();
builder.Providers.AddAuthorization();
builder.Providers.AddIdentityApiEndpoints<IdentityUser>()
    .AddEntityFrameworkStores<CustomDbContext>();
builder.Providers.AddEndpointsApiExplorer();
builder.Providers.AddSwaggerGen();
var app = builder.Construct();
app.MapIdentityApi<IdentityUser>();

The AddIdentityApiEndpoints() methodology within the previous code snippet provides the mandatory controllers and companies for authentication and authorization (login, logout, registration, and so forth.). Be aware that it is a new methodology (launched in .NET 8) used to configure Id integration in an software. The AddIdentityApiEndpoints() methodology accepts an occasion of kind IdentityUser as a parameter, which is used to specify the kind of consumer.

You should use the next piece of code so as to add authorization for the /helloworld endpoint.

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

Full supply of the Program.cs file

The whole supply code of the Program.cs file is given beneath on your reference.

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

The built-in identification administration function in ASP.NET Core is each highly effective and straightforward to make use of. The enhancements in .NET 8 have made Id much more strong and versatile with an improved Id API, which lets you implement identity-based  authentication and authorization extra simply and effectively with much less code.

Copyright © 2024 IDG Communications, Inc.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay Connected

0FansLike
3,912FollowersFollow
0SubscribersSubscribe
- Advertisement -spot_img

Latest Articles