How can I get user information from a JWT token in ASP.NET Core 8?

880 views Asked by At

I'm writing a client-server application with JWT authorization in ASP.NET Core 8.

Authorization API endpoints are implemented using the AddIdentityApi extension method added in .NET 8.

The problem is this: I need to get user information from the JWT token body in my SPA application, but the endpoints added by AddIdentityApi are return a responses with encrypted(compressed?) tokens - these tokens do not have dots as a delimiter.

Login response example:

{
  "tokenType": "Bearer",
  "accessToken": "CfDJ8GwmsrOCkNBF ... ",    <-- long string without dots
  "expiresIn": 3600,
  "refreshToken": "..."
}

Previously I used JWT tokens in ASP.NET and they were readable.

I couldn't find the layer in the authentication system that does this encryption and I don't understand why it is encrypted. The HttpContext.User of authorized requests contains all the information I need.

My Program.cs:

using ICollector.Server.Data;
using ICollector.Server.Models;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<AppIdentityDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("mssql")
        ?? throw new InvalidOperationException("Connection string not found.")));

builder.Services.AddIdentityApiEndpoints<AppUser>()
    .AddEntityFrameworkStores<AppIdentityDbContext>();

builder.Services.AddAuthorization();

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

var app = builder.Build();

app.UseHttpsRedirection();

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

app.UseDefaultFiles();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapGroup("/api/identity").MapIdentityApi<AppUser>();

app.MapFallbackToFile("/index.html");

app.Run();

I read this article by Andrew Lock where he described the new functionality, but I did not find any explanation about the token format there.

Digging into the framework code, I found a static class JwtTokenUtilities, which has a method DecompressToken(byte[] tokenBytes, string algorithm), from which I can conclude that compression can be performed, but is it done in my configuration and I still don’t understand what the algorithm is.

0

There are 0 answers