当前位置:网站首页>. 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 .
边栏推荐
- File system notes
- Application of intelligent reservoir management based on 3D GIS system
- On BOM and DOM (2): DOM node hierarchy / attributes / Selectors / node relationships / detailed operation
- 文件系统笔记
- FreeRTOS MPU使系统更健壮!
- 多传感器融合track fusion
- C language student management system - can check the legitimacy of user input, two-way leading circular linked list
- The three-year action plan of the Ministry of industry and information technology has been announced, and the security industry has ushered in major development opportunities!
- 展锐芯片之GPU频率
- How do I turn off win10 automatic update? What are the good ways?
猜你喜欢

leetcode:84. 柱状图中最大的矩形

You have a chance, here is a stage
![[binary tree] - middle order traversal of binary tree](/img/93/442bdbecb123991dbfbd1e5ecc9d64.png)
[binary tree] - middle order traversal of binary tree

leetcode:1856. Maximum value of minimum product of subarray

setInterval里面的函数不能有括号

数据库 存储过程 begin end

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

年中了,准备了少量的自动化面试题,欢迎来自测

Rockscache schematic diagram of cache operation

oracle sql综合运用 习题
随机推荐
If you want to learn programming well, don't recite the code!
C语言学生管理系统——可检查用户输入合法性,双向带头循环链表
leetcode:84. 柱状图中最大的矩形
线程安全与实现方法
目标5000万日活,Pwnk欲打造下一代年轻人的“迪士尼乐园”
Let's talk about BOM and DOM (5): dom of all large Rovers and the pits in BOM compatibility
原神方石机关解密
虚拟文件系统
LuChen technology was invited to join NVIDIA startup acceleration program
数据库 存储过程 begin end
Command ‘[‘where‘, ‘cl‘]‘ returned non-zero exit status 1.
Rockscache schematic diagram of cache operation
机器人迷雾之算力与智能
展锐芯片之GPU频率
多传感器融合track fusion
项目Demo
Record -- about the method of adding report control to virtual studio2017 -- reportview control
Thread safety and its implementation
Go operation SQLite code error
Easy car Interviewer: talk about MySQL memory structure, index, cluster and underlying principle!