Wednesday, August 16, 2023

ASP.NET Core 8.0 Preview: All New Identity Endpoints

In this post let's have a look at brand new Identity endpoints which is available with ASP.NET 8 Preview 7.

To get started, let's create a new ASP.NET Core Web API project targeting .NET 8. Now install the latest previews of the following packages.

<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.0-preview.7.23375.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.0-preview.7.23375.4" />

And update the Program.cs as follows.

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

// Add authentication
builder.Services
    .AddAuthentication()
    .AddBearerToken(IdentityConstants.BearerScheme);

// Add Authorization
builder.Services.AddAuthorizationBuilder();

// Add DbContext
builder.Services
    .AddDbContext<AppDbContext>(options => options.UseInMemoryDatabase("AppDb"));

// Map Identity System
// Specify the DbContext for the identity store
// Opt-in to use the new endpoints
builder.Services
    .AddIdentityCore<MyUser>()
    .AddEntityFrameworkStores<AppDbContext>()
    .AddApiEndpoints();

builder.Services
    .AddEndpointsApiExplorer()
    .AddSwaggerGen();

WebApplication app = builder.Build();

// Map Identity API Endpoints to Middleware
app.MapIdentityApi<MyUser>();

app
    .MapGet("/", (ClaimsPrincipal user) => $"Hello {user.Identity!.Name}")
    .RequireAuthorization();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.Run();

class MyUser : IdentityUser { }

class AppDbContext : IdentityDbContext<MyUser>
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
}

I have added inline comments, so it is easy to follow.

And now when I run the application, I can see all the Identity endpoints.

Swagger UI - Identity API
You can use the following .http file to test the main endpoints.

@url=https://localhost:7015
@user=user1
@password=P@ssw0rd!
@email=user1@test.com

# Register User
POST {{url}}/register
Content-Type: application/json

{
  "username": "{{user}}",
  "password": "{{password}}",
  "email": "{{email}}"
}

# Login
POST {{url}}/login
Content-Type: application/json

{
  "username": "{{user}}",
  "password": "{{password}}"
}

# Call secured endpoint
@token=<your token here>
GET {{url}}
Authorization: Bearer {{token}}

David Fowler (@davidfowl) has created a nice example that you can fork and try out.
   davidfowl/IdentityEndpointsSample

Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment