当前位置:网站首页>.NET7之MiniAPI(特别篇) :Preview5优化了JWT验证(上)
.NET7之MiniAPI(特别篇) :Preview5优化了JWT验证(上)
2022-06-24 06:39:00 【dotNET跨平台】
在.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相关,它们分别拥有的命令如下图:


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

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

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

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

上面只是验证,那如果增加角色呢?先在项目中添加代码:
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

dotnet user-jwts create --name=桂素伟 --role=admin
创建一个名字叫桂素伟,角色是admin的token。
这时,再次测试结果如下,这次name和role都是自己设置的了。

通过上面的两个例子,可以看到,通过这两组工具,可以帮我们生成token,可以直接用来测试,而不需要提前把获取tokne和权限相关的东西搞定,虽然只是一小步,也说明了.net7在进步中。
边栏推荐
- 潞晨科技获邀加入NVIDIA初创加速计划
- What are the easy-to-use character recognition software? Which are the mobile terminal and PC terminal respectively
- Use of SQL join
- Microsoft Security, which frequently swipes the network security circle, gives us some enlightenment this time?
- 35 year old crisis? It has become a synonym for programmers
- How does easyplayer RTSP configure sending heartbeat information to the server?
- Easy car Interviewer: talk about MySQL memory structure, index, cluster and underlying principle!
- Record -- about the method of adding report control to virtual studio2017 -- reportview control
- Domain name purchase method good domain name selection principle
- What are the audio formats? Can the audio format be converted
猜你喜欢

应用配置管理,基础原理分析

Leetcode: Sword finger offer 26: judge whether T1 contains all topologies of T2

35 year old crisis? It has become a synonym for programmers

【二叉数学习】—— 树的介绍

Application configuration management, basic principle analysis

Record -- about the problem of garbled code when JSP foreground passes parameters to the background

智能视觉组A4纸识别样例

Localized operation on cloud, the sea going experience of kilimall, the largest e-commerce platform in East Africa

The data synchronization tool dataX has officially supported reading and writing tdengine

记录--关于virtual studio2017添加报表控件的方法--Reportview控件
随机推荐
Flutter environment installation & operation
项目Demo
Arduino融资3200万美元,进军企业市场
Internet cafe management system and database
leetcode:剑指 Offer 26:判断t1中是否含有t2的全部拓扑结构
Command ‘[‘where‘, ‘cl‘]‘ returned non-zero exit status 1.
Application of O & M work order
puzzle(019.1)Hook、Gear
About Stacked Generalization
The 2021 Tencent digital ecology conference landed in Wuhan, waiting for you to come to the special session of wechat with low code
Oceanus kudu sink summary
Virtual file system
Domain name purchase method good domain name selection principle
年中了,准备了少量的自动化面试题,欢迎来自测
Online font converter what is the meaning of font conversion
目标5000万日活,Pwnk欲打造下一代年轻人的“迪士尼乐园”
Why the computer can't start
On BOM and DOM (1): overview of BOM and DOM
leetcode:84. 柱状图中最大的矩形
Deploy DNS server using dnsmasq