ASP.NET 8 Introduces a New Authentication and Authorization Mechanism

.NET 8 is soon coming, and it introduces some intriguing features, particularly in ASP.NET Core authentication and authorization. For ASP.NET Core Identity, one major change is the transition from a page-oriented to an API-oriented approach. Let’s go into the specifics.

Token-based Authentication with ASP.NET Core Identity

ASP.NET Core developers use the built-in ASP.NET Core Identity framework for local authentication and authorization. This framework contains all of the components required to manage user authentication and authorization against a local user store. It generates a SQL Server database on Windows by default and a SQLite database on macOS, but you can change it to your favorite DBMS.

While ASP.NET Core Identity is ideal for server-rendered web projects such as ASP.NET Core MVC or Razor Pages, it has limitations when it comes to Single Page Applications (SPAs), where token-based authentication is preferable. Since.NET Core 3.1, Microsoft has provided project templates for SPAs using Angular and React, as well as Identity Server compatibility. This method, however, did not totally satisfy the community.

Microsoft implemented modifications in.NET 8 in response to community feedback. They removed default support for the Identity Server and redesigned ASP.NET Core Identity’s core architecture to better suit SPAs and native apps. .NET 8 adds new Identity API endpoints and allows token-based authentication. Let’s take these enhancements one at a time.

Handler for Bearer Token Authentication

The bearer token authentication handler is the core of this new setup. This handler functions similarly to the classic cookie authentication handler used by ASP.NET Core Identity. The cookie authentication handler has two purposes.

  • After the user logs in, a new session cookie is created.
  • Constructs a ClaimsPrincipal user object from an incoming HTTP request using a valid session cookie.

Similarly, the bearer token authentication handler is responsible for two things.

  • After the user logs in, a new token is generated.
  • Based on a valid token from the incoming HTTP request, this method creates a ClaimsPrincipal user object.

In layman’s terms, the bearer token handler functions similarly to the cookie handler, but maintains authorized sessions with a token rather than 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 is divided into two parts.

Endpoint of Login
When you visit the “/login” web address and enter a username, the application generates a unique user based on that username.
It then indicates whether or not the sign-in process was successful.

Endpoint User
The “/user” web address displays the username of the user who is presently logged in.

There are references in the code to a new tool called “BearerToken” that aids in the safe management of user identities. It also prepares this tool for use by adding some required 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 Peter

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.

Best and Most Recommended ASP.NET Core 8 Hosting

Fortunately, there are a number of dependable and recommended web hosts available that can help you gain control of your website’s performance and improve your ASP.NET Core 8 web ranking. HostForLIFEASP.NET is highly recommended. In Europe, HostForLIFEASP.NET is the most popular option for first-time web hosts searching for an affordable plan.

Their standard price begins at only € 3.49 per month. Customers are permitted to choose quarterly and annual plans based on their preferences. HostForLIFEASP.NET guarantees “No Hidden Fees” and an industry-leading ’30 Days Cash Back’ policy. Customers who terminate their service within the first thirty days are eligible for a full refund.

By providing reseller hosting accounts, HostForLIFEASP.NET also gives its consumers the chance to generate income. You can purchase their reseller hosting account, host an unlimited number of websites on it, and even sell some of your hosting space to others. This is one of the most effective methods for making money online. They will take care of all your customers’ hosting needs, so you do not need to fret about hosting-related matters.