当前位置:网站首页>. Net7 miniapi (special part):preview5 optimizes JWT verification (Part 1)
. Net7 miniapi (special part):preview5 optimizes JWT verification (Part 1)
2022-06-24 07:01:00 【Dotnet cross platform】
stay .NET7 Of Preview5 in , To optimize the asp.net core Medium JWT verification , Don't be as cumbersome as before , More importantly, it brings a set of generation Token Tools for , It allows developers or testers to access without logging in Token, And achieve the purpose of testing .
Create project
Now let's see how to use , Preferred to create project ,/ No verification ,/myhome Yes, there is verification
var builder = WebApplication.CreateBuilder(args);
builder.Authentication.AddJwtBearer();
app.MapGet("/", () => " No validation ");
app.MapGet("/myhome", (ClaimsPrincipal user) => $" Hello {user.Identity?.Name}, Welcome to your homepage ")
.RequireAuthorization();
app.Run();Use tools to generate Token
Two tools are introduced this time user-secrets and user-jwts, By name , You can also learn that one is related to encryption , One and JWT Of token relevant , Their respective commands are shown in the following figure :


1、 If used for the first time in the project user-secrets Tools , First, initialize , You can right-click the item , use “ Open at terminal ”, To run the command line .
dotnet user-secrets init
The return result of the command is :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'.
meanwhile , This command will generate... In the project file UserSecretsID node , The value is exactly what is returned above UUID
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>preview</LangVersion>
<UserSecretsId>c2450184-8525-4ed7-9a82-d54c349dd4b8</UserSecretsId>
</PropertyGroup>2、 Now take a look secrets, The result is no configuration
dotnet user-secrets list
No secrets configured for this application.
3、 If you look at jwts, The return value is as follows , Yes Secrets, But there is no 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、 This is the time to create a jwt
dotnet user-jwts create
New JWT saved with ID 'd7dabed0'.
"Authentication": {
"Schemes": {
"Bearer": {
"Audiences": [
"http://localhost:5274"
],
"ClaimsIssuer": "dotnet-user-jwts"
}
}
}meanwhile , Will be in C:\Users\axzxs\AppData\Roaming\Microsoft\UserSecrets Generate a secrets Folder , There are two files in it secrets.json and user-jwts.json, There are generated secret Information and jwt Information .
5、 At this time secrets Show me again , It will be worth it
dotnet user-secrets list
Return results :
dotnet-user-jwts:KeyMaterial = l4ynAWIVR5JKSKo5Yyr0XvOXgZ+dlBUwe3jI1st3DsY=
6、jwts list, There will be a list
dotnet user-jwts list

7、 It can be used jwts Of print command , Show me token, So that we can use it in the test
dotnet user-jwts print d7dabed0 --show-full

Running results
Run the project , use postman test , There's no problem with this , Return no validation

Copy the generated Token, Put it in header in , request myhome, At this time, the information that has passed the verification will be returned , And with name, This name Is the current windows user

The above is just verification , What about adding roles ? Add code to the project first :
app.MapGet("/order", (ClaimsPrincipal user) => $" user :{user.Identity?.Name}, You are a :{user.Claims?.Where(s => s.Type == ClaimTypes.Role).First().Value} role , This is your exclusive page ").RequireAuthorization(builder =>
{
builder.RequireRole("admin");
});The one with the character token How to generate ? Have a look first user-jwts create Aid of command , Yes, you can. create Time plus name and role Of .
dotnet user-jwts create --help

dotnet user-jwts create --name= Gui Suwei --role=admin
Create a project named guisuwei , The role is admin Of token.
At this time , Again, the test results are as follows , This time, name and role It's all set up by myself .

Through the above two examples , You can see , Through these two sets of tools , Can help us generate token, Can be directly used to test , There is no need to get in advance tokne Things related to permissions are done , It's just a small step , Also explained .net7 In progress .
边栏推荐
- Go excel export tool encapsulation
- How do I reinstall the system? How to install win10 system with USB flash disk?
- Oceanus kudu sink summary
- You have a chance, here is a stage
- How to send SMS in groups? What are the reasons for the poor effect of SMS in groups?
- How long does the domain name filing take and what materials need to be prepared
- 35岁危机?内卷成程序员代名词了
- 多传感器融合track fusion
- 面渣逆袭:MySQL六十六问,两万字+五十图详解
- Surveying and mapping principle of GIS coordinate system: geoid / datum / reference ellipsoid /epsg/sri/wkt
猜你喜欢

【二叉树】——二叉树中序遍历

Internet cafe management system and database

Database stored procedure begin end

puzzle(019.1)Hook、Gear

You have a chance, here is a stage

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

leetcode:85. Max rectangle

FreeRTOS MPU使系统更健壮!

成为 TD Hero,做用技术改变世界的超级英雄 | 来自 TDengine 社区的邀请函

35 year old crisis? It has become a synonym for programmers
随机推荐
潞晨科技获邀加入NVIDIA初创加速计划
Spark累加器和广播变量
智能视觉组A4纸识别样例
RealNetworks vs. 微软:早期流媒体行业之争
多传感器融合track fusion
网吧管理系统与数据库
35岁危机?内卷成程序员代名词了
LuChen technology was invited to join NVIDIA startup acceleration program
FreeRTOS MPU使系统更健壮!
Open source and innovation
数据同步工具 DataX 已经正式支持读写 TDengine
leetcode:剑指 Offer 26:判断t1中是否含有t2的全部拓扑结构
MAUI使用Masa blazor组件库
Another double win! Tencent's three security achievements were selected into the 2021 wechat independent innovation achievements recommendation manual
Kubernets traifik proxy WS WSS application
C语言学生管理系统——可检查用户输入合法性,双向带头循环链表
Actual combat | how to deploy flask project using wechat cloud hosting
Le système de surveillance du nuage hertzbeat v1.1.0 a été publié, une commande pour démarrer le voyage de surveillance!
Localized operation on cloud, the sea going experience of kilimall, the largest e-commerce platform in East Africa
Surveying and mapping principle of GIS coordinate system: geoid / datum / reference ellipsoid /epsg/sri/wkt