New feature for Authentication and Authorization in .NET 8

.NET 8 is almost here, and it brings some exciting changes, especially for authentication and authorization in ASP.NET Core. One notable shift is moving from a page-oriented approach to an API-oriented approach for ASP.NET Core Identity. Let's dive into the details.

ASP.NET Core Identity and Token-based Authentication

For local authentication and authorization, ASP.NET Core developers rely on the built-in ASP.NET Core Identity framework. This framework provides everything needed to manage user authentication and authorization against a local user store. By default, it creates an SQL Server database on Windows and a SQLite database on macOS, but you can switch to your preferred DBMS.

While ASP.NET Core Identity is great for server-rendered web apps like ASP.NET Core MVC or Razor Pages, it faces challenges with Single Page Applications (SPAs) where token-based authentication is more suitable. To address this, Microsoft offered project templates for SPAs with Angular and React and Identity Server support since .NET Core 3.1. However, this approach didn't completely satisfy the community.

In response to community feedback, Microsoft made changes in .NET 8. They removed default support for the Identity Server and revamped the internal architecture of ASP.NET Core Identity to better suit SPAs and native apps. .NET 8 introduces a new set of Identity API endpoints and supports token-based authentication. Let's explore these improvements step by step.

Bearer Token Authentication Handler

The foundation of this new setup is the bearer token authentication handler. This handler works similarly to the traditional cookie authentication handler that ASP.NET Core Identity typically uses. The cookie authentication handler does two main things.

  1. Creates a new session cookie after the user logs in.
  2. Constructs a ClaimsPrincipal user object using a valid session cookie from the incoming HTTP request.

Likewise, the bearer token authentication handler has two main responsibilities.

  1. Generates a new token after the user logs in.
  2. Constructs a ClaimsPrincipal user object based on a valid token from the incoming HTTP request.

In simpler terms, the bearer token handler behaves like the cookie handler but manages authenticated sessions using a token instead of a cookie.

Example Code. // Program.cs 

using Microsoft.AspNetCore.Authentication.BearerToken;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System.Security.Claims;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication()
    .AddBearerToken();

builder.Services.AddAuthorization();

var app = builder.Build();

app.MapGet("/login", (string username) =>
{
    var claimsPrincipal = new ClaimsPrincipal(
        new ClaimsIdentity(
            new[] { new Claim(ClaimTypes.Name, username) },
            BearerTokenDefaults.AuthenticationScheme
        )
    );

    return Results.SignIn(claimsPrincipal);
});

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

app.Run();

This program has two parts.

  1. Login Endpoint
    When you go to the "/login" web address and provide a username, the program creates a special user based on that username.

    • It then shows whether the sign-in process was successful.
  2. User Endpoint
    If you go to the "/user" web address, it tells you the username of the user who is currently signed in.

In the code, you see references to a new tool called "BearerToken" which helps manage user identities securely. It also sets up this tool for use by adding some necessary code lines.

If you run the command.

curl 'https://<YOUR_HOST>/login?username=MaheshChandraSir'

You will see a result like the following.

{
  "token_type": "Bearer",
  "access_token": "CfDJ8Ha5YkqG...omitted content...",
  "expires_in": 3600,
  "refresh_token": "CfDJ8Ha5YkqG...omitted content..."
}

This JSON contains an access token and a refresh token that you can use to make your calls to the protected APIs exposed by your application. For example, you can now call the protected /user endpoint as follows.

curl -i https://<YOUR_HOST>/user \
-H 'Authorization: Bearer CfDJ8Ha5YkqG...omitted content...'

And you will get the following response.

Welcome MaheshChandraSir!

Summary

The bearer token authentication handler makes it very easy to set up token-based authentication. This is the building block of the whole ASP.NET Core Identity transition to token-based authentication.


Similar Articles
Citiustech Healthcare Technology Pvt Ltd
CitiusTech plays a deep and meaningful role in powering the future of healthcare.