.net core: generate jwt token based on parameters passed into AddBearerToken

586 Views Asked by At

When I look into setting up JWT authentication for a web API I see the following process:

To your services:

services.AddAuthentication().AddJwtBearer(o =>
{
    o.TokenValidationParameters = new TokenValidationParameters
    { 
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["secrets"]))
    };
});

Next step all documentations I have seen talk about is: in order to generate the token, use some helper classes and pass the configurations such as secrets and issuer again. This never made much sense to me. Since the AddJwtBearer function has already taken in all configurations, isn't there a function as straightforward as httpContext.GenerateJwt(new Claims[]{}) that would generate the token? Why would we need to use so much boilerplate?

I have been looking for a function like this since .NET 2.0. I create a NuGet to do exactly this (so I know what I am talking about is feasible and straightforward to implement). However, this NuGet no longer works with .NET 6.0. Instead of fixing my NuGet, I wanted to check if the .NET Core has a clean solution for generating JWT tokens yet.

1

There are 1 best solutions below

11
Tore Nestenius On

The AddJwtBearer token handler is only meant to be used in APIs receiving API tokens. There is no logic to generate JWT tokens. JWT Tokens are usually generated by your token provider (like IdentityServer).

The problem with generating your own tokens is the signature, you need to pass the public signing key to AddJwtBearer, for it to be able to accept the JWT tokens.

If you want to generate your own token for testing, then there is a tool called user-jwts. Manage JSON Web Tokens in development with dotnet user-jwts

I also have a set of blog posts about the JWtBearer handler here: https://nestenius.se/2023/02/21/troubleshooting-jwtbearer-authentication-problems-in-asp-net-core/

By default, we use the JwtSecurityTokenHandler library to create and verify tokens

enter image description here

A more optimized version exists named JsonWebTokenHandler.