Monday, August 7, 2023

ASP.NET Core 8.0 Preview: All New AddBearerToken Extensions

With ASP.NET Core 8.0 Preview, we now have some new AddBearerToken extension methods on Microsoft.AspNetCore.Authentication.AuthenticationBuilder. It seems to have been introduced as part of ASP.NET Core 8.0 Preview 4: Microsoft.Extensions.DependencyInjection.BearerTokenExtensions)

 Note: this is for Bearer Tokens and not JSON Web Tokens (JWT).

Let's go by an example. Make sure your project's Target Framework is .NET 8.0.
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <InvariantGlobalization>true</InvariantGlobalization>
  </PropertyGroup>

</Project>
I can now add bearer token authentication as follows.
using Microsoft.AspNetCore.Authentication.BearerToken;
using System.Security.Claims;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

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

WebApplication app = builder.Build();

app.UseHttpsRedirection();

app
    .MapPost("/login", (Dictionary<stringstringkeyValuePairs) =>
    {
        IEnumerable<Claim> claims = keyValuePairs.Select(x => new Claim(x.Key, x.Value));
        ClaimsPrincipal claimsPrinciple = 
            new(new ClaimsIdentity(claims, BearerTokenDefaults.AuthenticationScheme));

        return Results.SignIn(claimsPrinciple);
    });

app
    .MapGet("/", (ClaimsPrincipal claimsPrincipal) =>
    {
        return Results.Ok(claimsPrincipal.Claims.Select(x => new { x.Type, x.Value }));
    })
    .RequireAuthorization();

app.Run();
Note the AddBearerToken() on AuthenticationBuilder.

I can try it out using the following .http file.
@hostname=localhost
@port=7285
@host={{hostname}}:{{port}}

POST https://{{host}}/login
Content-Type: application/json

{
    "name": "John",
    "role": "administrator"
}

# Replace the token below with the access_token returned from the previous request
GET https://{{host}}
Authorization: Bearer CfDJ8HM03LdIurJAspnEgIvCgGvRg4CERoTTGFrsX-2P_XJaCwdzo8bH6DoKZgL51KM_W8Qr1iB8U3XKatYAVMLubrqXJmkPWOATrGudmGEcGINZwl04m1Eue6U-fyYTevKGZG-dSyKPmtaYBbHqSiknhLe07VlUTFgLHDGw1Yd6m5A4N4KFZkj9fB7Ciyfn3YoBanEyXQTqGxOntz_hnVazocL6xONaIThfGmHx3kgLMjG72Vfte8cp0cV89u1cXzkTTapPz2k9yXuCBjgO-Oks49OVRCTETQcdd5vIyV1xJTkKWyGaQOxkImtwDoUqPE1rwA
.http
Isn't it handy? 

Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment