26 C
New York
Thursday, May 23, 2024

Find out how to implement id authentication in minimal APIs in ASP.NET Core


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

We mentioned implementing fundamental authentication in minimal APIs right here, and JWT token-based authentication in minimal APIs right here. On this article we’ll study 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, you need to have Visible Studio 2022 put in in your system. If you happen to don’t have already got a replica, you may obtain Visible Studio 2022 right here.

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

To create an ASP.NET Core Net API undertaking in Visible Studio 2022, comply with the steps outlined beneath.

  1. Launch the Visible Studio 2022 IDE.
  2. Click on on “Create new undertaking.”
  3. Within the “Create new undertaking” window, choose “ASP.NET Core Net API” from the listing of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new undertaking” window, specify the title and site for the brand new undertaking. Optionally verify the “Place answer and undertaking in the identical listing” verify field, relying in your preferences.
  6. Click on Subsequent.
  7. Within the “Further Info” window proven subsequent, choose “.NET 8.0 (Lengthy Time period Help)” because the framework model and uncheck the verify field that claims “Use controllers,” as we’ll be utilizing minimal APIs on this undertaking.
  8. Elsewhere within the “Further Info” window, depart the “Authentication Kind” set to “None” (the default) and ensure the verify containers “Allow Open API Help,” “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 undertaking 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 generally known as id administration that has been enhanced in .NET 8. The built-in Id framework in ASP.NET Core supplies the mandatory middleware to implement authentication, person administration, and role-based authorization, thereby making it easier to implement sturdy 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
  • Consumer administration
  • Roles administration
  • Password hashing
  • Token-based authentication
  • Claims-based authentication

Create a minimal API in ASP.NET Core

Within the Net API undertaking we created above, substitute the generated code with the next code to create a fundamental minimal API.

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

While you execute the applying, the textual content “Whats up World!” will probably be displayed in your net 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 undertaking 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){ } 

You need to register the customized DbContext class by together with the next line of code within the Program.cs file.

builder.Companies.AddDbContext<CustomDbContext>();

Allow authentication and authorization in ASP.NET Core

Authentication is the method of figuring out who the person is and validating the person’s id. You possibly can allow authentication in a minimal API in ASP.NET Core by utilizing the AddAuthentication() methodology as proven within the code snippet given beneath.

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

We use authorization to limit entry to sure assets in an software. You possibly can allow authorization in your minimal API by utilizing the next code.

builder.Companies.AddAuthorization();

The AddAuthorization methodology is used to register authorization companies with the companies container with the intention to outline guidelines for enabling or disabling entry to assets of the applying if wanted.

Configure companies and API endpoints in ASP.NET Core

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

utilizing Microsoft.AspNetCore.Id;
utilizing Microsoft.AspNetCore.Id.EntityFrameworkCore;
utilizing Microsoft.EntityFrameworkCore;
builder.Companies.AddDbContext<CustomDbContext>();
builder.Companies.AddAuthorization();
builder.Companies.AddIdentityApiEndpoints<IdentityUser>()
    .AddEntityFrameworkStores<CustomDbContext>();
builder.Companies.AddEndpointsApiExplorer();
builder.Companies.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 on.). 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 sort IdentityUser as a parameter, which is used to specify the kind of person.

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

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

Full supply of the Program.cs file

The entire supply code of the Program.cs file is given beneath in 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.Companies.AddDbContext<CustomDbContext>();
builder.Companies.AddAuthorization();
builder.Companies.AddIdentityApiEndpoints<IdentityUser>()
    .AddEntityFrameworkStores<CustomDbContext>();
builder.Companies.AddEndpointsApiExplorer();
builder.Companies.AddSwaggerGen();
var app = builder.Construct();
app.MapIdentityApi<IdentityUser>();
// Configure the HTTP request pipeline.
app.MapGet("/helloworld", () => "Whats up 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 id administration function in ASP.NET Core is each highly effective and simple to make use of. The enhancements in .NET 8 have made Id much more sturdy 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.



Supply hyperlink

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles