当前位置:网站首页>. 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 :

367befaa6dafbe07e2e31e45d2cdb157.png

02b4eae3f697e68e7d44f7c6c17c5369.png

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

09bfac17d8aa333cb3f38bd1b450a7dc.png

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

94cb4de7ace232a0019198e7c49282ca.png

Running results

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

9499e2faccebb8d44d4775a9ffb6f4ff.png

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

00c24dcdff60273ccf4f94dd4e312ef6.png

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

1e83ea37f9baf3f72971b56f10bdf73c.png

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 .

7cf602d8a1cdeaca8c4fb4233579bf4d.png

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 .

原网站

版权声明
本文为[Dotnet cross platform]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240047064900.html