当前位置:网站首页>. 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 .
边栏推荐
- 原神方石机关解密
- When the VPC main network card has multiple intranet IP addresses, the server cannot access the network internally, but the server can be accessed externally. How to solve this problem
- Distributed cache breakdown
- 应用配置管理,基础原理分析
- typescript vscode /bin/sh: ts-node: command not found
- [binary number learning] - Introduction to trees
- File system notes
- Produce kubeconfig with permission control
- 面渣逆袭:MySQL六十六问,两万字+五十图详解
- Surveying and mapping principle of GIS coordinate system: geoid / datum / reference ellipsoid /epsg/sri/wkt
猜你喜欢

MAUI使用Masa blazor组件库
![跳跃游戏II[贪心练习]](/img/e4/f59bb1f5137495ea357462100e2b38.png)
跳跃游戏II[贪心练习]

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

About Stacked Generalization

leetcode:剑指 Offer 26:判断t1中是否含有t2的全部拓扑结构

Oracle SQL comprehensive application exercises

面渣逆袭:MySQL六十六问,两万字+五十图详解

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

leetcode:84. The largest rectangle in the histogram

Challenges brought by maker education to teacher development
随机推荐
On BOM and DOM (3): DOM node operation - element style modification and DOM content addition, deletion, modification and query
Go operation SQLite code error
sql join的使用
Overview of new features in mongodb5.0
C language student management system - can check the legitimacy of user input, two-way leading circular linked list
记录--关于virtual studio2017添加报表控件的方法--Reportview控件
年中了,准备了少量的自动化面试题,欢迎来自测
十年
多传感器融合track fusion
leetcode:84. 柱状图中最大的矩形
What are the easy-to-use character recognition software? Which are the mobile terminal and PC terminal respectively
Station B collapsed. Let's talk to the injured programmers
应用配置管理,基础原理分析
Record -- about the problem of garbled code when JSP foreground passes parameters to the background
开源与创新
Do you know about Statistics?
File system notes
【二叉树】——二叉树中序遍历
puzzle(019.1)Hook、Gear
Code scanning | a sharp tool for controlling code quality