.NET7之MiniAPI(特别篇) :Preview5优化了JWT验证(上)

在.NET7的Preview5中,优化了asp.net core中的JWT验证,不用像以前繁琐了,更重要的是带来了一组生成Token的工具,可以让开发人员或测试人员不需登录获取Token,而达到测试的目的。.

创建项目

现在来看一下怎么使用,首选创建项目,/是无验证,/myhome是有验证

var builder = WebApplication.CreateBuilder(args);builder.Authentication.AddJwtBearer();app.MapGet("/", () => "无验证");app.MapGet("/myhome", (ClaimsPrincipal user) => $"你好 {user.Identity?.Name},欢迎来到你的主页")    .RequireAuthorization();app.Run();

用工具生成Token

本次共引入了两个工具user-secrets和user-jwts,通过名称,大家也能了解到一个是和加密相关,一个和JWT的token相关,它们分别拥有的命令如下图:

.NET7之MiniAPI(特别篇) :Preview5优化了JWT验证(上)

.NET7之MiniAPI(特别篇) :Preview5优化了JWT验证(上)

1、如果在项目中第一次使用user-secrets工具,首先要初始化,可以在右击项目,用“在终端打开”,来运行命令行。

dotnet user-secrets init

命令的返回结果是:Set UserSecretsId to 'c2450184-8525-4ed7-9a82-d54c349dd4b8' for MSBuild project 'C:\myfile\Source\Repos\Asp.NetCoreExperiment\Asp.NetCoreExperiment\MiniAPI\MiniAPI7_NewJWT\MiniAPI7_NewJWT.csproj'.

同时,这个命令会在项目文件中生成UserSecretsID节点,值正是上面返回的UUID

<PropertyGroup>  <TargetFramework>net7.0</TargetFramework>  <Nullable>enable</Nullable>  <ImplicitUsings>enable</ImplicitUsings>  <LangVersion>preview</LangVersion>  <UserSecretsId>c2450184-8525-4ed7-9a82-d54c349dd4b8</UserSecretsId></PropertyGroup>

2、这时看一下secrets,结果是没有配置

dotnet user-secrets list

No secrets configured for this application.

3、如果看一下jwts,返回值如下,有Secrets,但没有jwts

dotnet user-jwts list

Project: C:\myfile\Source\Repos\Asp.NetCoreExperiment\Asp.NetCoreExperiment\MiniAPI\MiniAPI7_NewJWT\MiniAPI7_NewJWT.csproj

User Secrets ID: c2450184-8525-4ed7-9a82-d54c349dd4b8

No JWTs created yet!

4、这个时候创建一个jwt

dotnet user-jwts create

New JWT saved with ID 'd7dabed0'.

  "Authentication": {    "Schemes": {      "Bearer": {        "Audiences": [          "http://localhost:5274"        ],        "ClaimsIssuer": "dotnet-user-jwts"      }    }  }
同时,会在C:\Users\axzxs\AppData\Roaming\Microsoft\UserSecrets生成一个secrets文件夹,里面有两个文件secrets.json和user-jwts.json,里面分别放着生成的secret信息和jwt信息。

5、这时secrets再显示一下,就会有值了

dotnet user-secrets list

返回结果:

dotnet-user-jwts:KeyMaterial = l4ynAWIVR5JKSKo5Yyr0XvOXgZ+dlBUwe3jI1st3DsY=

6、jwts list,就会有列表了

dotnet user-jwts list

.NET7之MiniAPI(特别篇) :Preview5优化了JWT验证(上)

7、可以用jwts的print命令,显示一下token,以方便我们在测试中使用

dotnet user-jwts print d7dabed0 --show-full

.NET7之MiniAPI(特别篇) :Preview5优化了JWT验证(上)

运行结果

运行项目,用postman测试,这个没有什么问题,返回无验证

.NET7之MiniAPI(特别篇) :Preview5优化了JWT验证(上)

复制生成的Token,放在header中,请求myhome,这时会返回验证通过的信息,并且带有name,这个name就是当前windows用户

.NET7之MiniAPI(特别篇) :Preview5优化了JWT验证(上)

上面只是验证,那如果增加角色呢?先在项目中添加代码:

app.MapGet("/order", (ClaimsPrincipal user) => $"用户:{user.Identity?.Name},您是:{user.Claims?.Where(s => s.Type == ClaimTypes.Role).First().Value}角色,这是你的专属页").RequireAuthorization(builder =>{    builder.RequireRole("admin");});
那带角色的token怎么生成呢?先看一下user-jwts create命令的帮助,是可以在create时加name和role的。

dotnet user-jwts create --help

.NET7之MiniAPI(特别篇) :Preview5优化了JWT验证(上)

dotnet user-jwts create --name=桂素伟 --role=admin

创建一个名字叫桂素伟,角色是admin的token。

这时,再次测试结果如下,这次name和role都是自己设置的了。

.NET7之MiniAPI(特别篇) :Preview5优化了JWT验证(上)

通过上面的两个例子,可以看到,通过这两组工具,可以帮我们生成token,可以直接用来测试,而不需要提前把获取tokne和权限相关的东西搞定,虽然只是一小步,也说明了.net7在进步中。