How ASP.NET validates bearer token?

52 Views Asked by At

So I have a very basic minimal api.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<IdentityDbContext>(options => options.UseInMemoryDatabase("AppDb"));
builder.Services.AddIdentityCore<User>()
    .AddEntityFrameworkStores<IdentityDbContext>()
    .AddApiEndpoints();

builder.Services.AddAuthentication().AddBearerToken(IdentityConstants.BearerScheme);
builder.Services.AddAuthorizationBuilder();

var app = builder.Build();

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

app.Run();

So I register, login then I get a bearer token which I can use to access my protected /test endpoint.

I would expect when I restart my application and lose all my data since I use InMemoryDb, I won't be able access my protected endpoint anymore but I can.

Now I don't understand why do Identity servieces require a DbContext to be registered when it dosn't validate the users in DbContext?

1

There are 1 best solutions below

2
Satya Tripathi On

The JWT is a self-contained token that has all the necessary information for authentication. It contains three parts: header, payload, and signature. The payload includes claims about the user, such as user ID, roles, etc. The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn't changed along the way.

When you send a request with a JWT, the server validates the token's signature and if it's valid, it trusts the claims in the payload without needing to check the database again. This is why you can still access your protected endpoint after restarting your application and losing all your data in the InMemoryDb.

The DbContext is not used to validate the token for each request, it's used to validate the user's credentials when they log in and to manage users and roles. The token validation is done by the JWT Bearer middleware which validates the signature and expiration of the token.

So, in your case, the token is still valid because it was issued before you restarted your application. If you want to invalidate tokens when you restart your application, you would need to implement a token revocation strategy. This usually involves storing issued tokens in a database and checking if they are still valid for each request, which adds more complexity and overhead to your application.