Wednesday, November 9, 2022

.NET: Using dotnet user-jwts to Create Development Time JWT Tokens

Hope you are enjoying .NET Conf 2022. It's such great content and another 2 more days to go. Don't miss it.

In this post, let's see how we can easily create JWT tokens for Development purposes using dotnet user-jwts

Consider the following code.
using System.Security.Claims;
 
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
 
// Add services to the container.
builder.Services.AddAuthentication()
    .AddJwtBearer();
 
builder.Services.AddAuthorization();
 
WebApplication app = builder.Build();
 
// Configure the HTTP request pipeline.
app.UseAuthorization();
 
app.UseHttpsRedirection();
 
app.MapGet("/", () => "Hello .NET");
 
app.MapGet("/me", (ClaimsPrincipal user) =>
    {
        return user?.Claims
            .Select(c => new { c.Type, c.Value })
            .ToList();
    })
    .RequireAuthorization();
 
app.Run();
So here, I have added the required services for Authentication/Authorization and have an endpoint that requires an authorized request. On a side note, here you can see I haven't specified the default authentication scheme when registering Authentication. We don't have to specify the default Authentication scheme anymore, if there is only one, it's automatically taken as the default and that's new with ASP.NET Core 7.0. 

Now back to the topic, how do we get a valid token for development purposes here easily?

We can use dotnet user-jwts to create JWT tokens and if we want, we can customize the token, like by adding different different scopes, claims, and so on, so we can dev test our authorization policies.

To get a valid token, we just need to run the following command from the Project directory.
dotnet user-jwts create
And this will give you an output like below.
dotnet user-jwts create
And at the same time, the command will update appsettings.Development.json, with few settings to validate the token in the Development environment.
{
  "Logging": {
    "LogLevel": {
      "Default""Information",
      "Microsoft.AspNetCore""Warning"
    }
  },
  "Authentication": {
    "Schemes": {
      "Bearer": {
        "ValidAudiences": [
          "http://localhost:35983",
          "https://localhost:44310",
          "http://localhost:5000",
          "https://localhost:7028"
        ],
        "ValidIssuer""dotnet-user-jwts"
      }
    }
  }
}
And now we can test the secured endpoint using a tool of our choice, passing the token that got generated under the Bearer scheme in the request's Authorization Header. If I use cURL, I can see I am getting authorized successfully.
Test the secured endpoint
That's pretty neat.

Read more about dotnet user-jwts command options to learn how you can customize the token.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment