1024programmer Asp.Net Using simplified AddJwtBearer authentication in NET8

Using simplified AddJwtBearer authentication in NET8

Using simplified AddJwtBearer authentication in NET8

Development environment

System version: win10
.NET SDK: NET8
Development tools: vscode
Reference: Managing JSON Web Tokens in Development using dotnet user-jwts
Note: The ports, tokens, etc. in the following examples need to be replaced with information in your environment

Create project

Run the following command to create an empty web project and add the Microsoft.AspNetCore.Authentication.JwtBearer NuGet package:

dotnet new web -o MyJWT
 cdMyJWT
 dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
 

Replace the contents of Program.cs with the following code (slightly modified):

using System.Security.Claims;

 var builder = WebApplication.CreateBuilder(args);

 builder.Services.AddAuthorization();
 //The default Scheme is Bearer
 // builder.Services.AddAuthentication("Bearer").AddJwtBearer();
 builder.Services.AddAuthentication().AddJwtBearer();

 var app = builder.Build();

 app.UseAuthorization();

 app.MapGet("/", () => "Hello, World!");
 app.MapGet("/secret", (ClaimsPrincipal user) => $"Hello {user.Identity?.Name}. My secret")
     .RequireAuthorization();

 app.Run();
 

Run the project and access the interface to return the following content

PS D:\Learn\MyJWT> curl.exe -i http:///localhost:5276
 HTTP/1.1 200 OK
 Content-Type: text/plain; charset=utf-8
 Date: Mon, 04 Dec 2023 00:43:03 GMT
 Server: Kestrel
 Transfer-Encoding: chunked

 Hello, World!
 

Create JWT

PS D:\Learn\MyJWT> dotnet user-jwts create
 New JWT saved with ID 'c28b968'.
 Name: Lingpeng

 Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IkxpbmdwZW5nIiwic3ViIjoiTGluZ3BlbmciLCJqdGkiOiJjMjhiOTY4IiwiYXVkIjpbImh0dHA6Ly9sb2Nhb Ghvc3Q6Mjk3NTQiLCJodHRwczovL2xvY2FsaG9zdDo0NDM2MCIsImh0dHA6Ly9sb2NhbGhvc3Q6NTI3NiIsImh0dHBzOi8vbG9jYWxob3N0OjcyNTMiXSwibmJmIjoxNzAxNjQ5Nzk2LCJleHAiO jE3MDk1MTIxOTYsImlhdCI6MTcwMTY0OTc5NiwiaXNzIjoiZG90bmV0LXVzZXItand0cyJ9.l52s9_7oNjIKL96TysgdE0k970fUS9FoLTu2xRs-IPo
 

This command does three things:

  1. Update the project’s appsettings.Development.json and add the Authentication node
  2. Updated the project’s MyJWT.csproj and added the UserSecretsId configuration
  3. Created secret files %APPDATA%\Microsoft\UserSecrets\\user-jwts.json and %APPDATA%\Microsoft\UserSecrets\\secrets.json , Confidentiality Management Reference

Let’s take a look at these two confidential documents
user-jwts.json

{
     "c28b968": {
         "Id": "c28b968",
         "Scheme": "Bearer",
         "Name": "Lingpeng",
         "Audience": "http://localhost:29754, https://localhost:44360, http://localhost:5276, https://localhost:7253",
         "NotBefore": "2023-12-04T00:29:56+00:00",
         "Expires": "2024-03-04T00:29:56+00:00",
         "Issued": "2023-12-04T00:29:56+00:00",
         "Token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IkxpbmdwZW5nIiwic3ViIjoiTGluZ3BlbmciLCJqdGkiOiJjMjhiOTY4IiwiYXVkIjpbImh0dHA6Ly9sb2N hbGhvc3Q6Mjk3NTQiLCJodHRwczovL2xvY2FsaG9zdDo0NDM2MCIsImh0dHA6Ly9sb2NhbGhvc3Q6NTI3NiIsImh0dHBzOi8vbG9jYWxob3N0OjcyNTMiXSwibmJmIjoxNzAxNjQ5Nzk2LCJleHA iOjE3MDk1MTIxOTYsImlhdCI6MTcwMTY0OTc5NiwiaXNzIjoiZG90bmV0LXVzZXItand0cyJ9.l52s9_7oNjIKL96TysgdE0k970fUS9FoLTu2xRs-IPo",
         "Scopes": [],
         "Roles": [],
         "CustomClaims": {}
     }
 }
 

secrets.json

{
     "Authentication:Schemes:Bearer:SigningKeys": [
         {
             "Id": "ff20683d",
             "Issuer": "dotnet-user-jwts",
             "Value": "lDOFmIuEDelFKU0zAaLoT2qYOFDRZGDDTv5FyTa36V8=",
             "Length": 32
         }
     ]
 }
 

Test JWT

We re-run the program and access the /secret interface using two methods: direct access and carrying token

PS D:\Learn\MyJWT> curl.exe -i http://localhost:5276/secret
 HTTP/1.1 401 Unauthorized
 Content-Length: 0
 Date: Mon, 04 Dec 2023 00:43:25 GMT
 Server: Kestrel
 WWW-Authenticate: Bearer

 PS D:\Learn\MyJWT>
 PS D:\Learn\MyJWT>
 PS D:\Learn\MyJWT> curl.exe -i -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IkxpbmdwZW5nIiwic3ViIjoiTGluZ3BlbmciLCJqdGkiOiJjMjhiOTY4Iiwi YXVkIjpbImh0dHA6Ly9sb2NhbGhvc3Q6Mjk3NTQiLCJodHRwczovL2xvY2FsaG9zdDo0NDM2MCIsImh0dHA6Ly9sb2NhbGhvc3Q6NTI3NiIsImh0dHBzOi8vbG9jYWxob3N0OjcyNTMiXSwib mJmIjoxNzAxNjQ5Nzk2LCJleHAiOjE3MDk1MTIxOTYsImlhdCI6MTcwMTY0OTc5NiwiaXNzIjoiZG90bmV0LXVzZXItand0cyJ9.l52s9_7oNjIKL96TysgdE0k970fUS9FoLTu2xRs-IPo" http://localhost: 5276/secret
 HTTP/1.1 200 OK
 Content-Type: text/plain; charset=utf-8
 Date: Mon, 04 Dec 2023 00:45:42 GMT
 Server: Kestrel
 Transfer-Encoding: chunked

 Hello Lingpeng. My secret
 

So far we have implemented the preliminary use of JwtBearer

A little change

The example uses secret management. We can also migrate the contents of the secret file to the project (secret management is recommended). We modify MyJWT.csproj and appsettings.Development.jsonAs follows



   
     net8.0
     enable
     enable
     <!-- 88d7c163-def1-4747-b01f-cefed382beae -->
   

   
     
   

 
 
{
   "Logging": {
     "LogLevel": {
       "Default": "Information",
       "Microsoft.AspNetCore": "Warning"
     }
   },
   "Authentication": {
     "Schemes": {
       "Bearer": {
         "ValidAudiences": [
           "http://localhost:29754",
           "https://localhost:44360",
           "http://localhost:5276",
           "https://localhost:7253"
         ],
         "ValidIssuer": "dotnet-user-jwts",
         "SigningKeys": [
           {
             "Id": "ff20683d",
             "Issuer": "dotnet-user-jwts",
             "Value": "lDOFmIuEDelFKU0zAaLoT2qYOFDRZGDDTv5FyTa36V8=",
             "Length": 32
           }
         ]
       }
     }
   }
 }
 

The same function will be achieved after modification

JWT Token generation example

app.MapGet("/login", (string UserName, string Password, [FromServices] IOptionsMonitor optionsMonitor) =>
 {
     // 1. Password verification
     // TODO

     // 2. Generate
     var parameters = optionsMonitor.Get(JwtBearerDefaults.AuthenticationScheme).TokenValidationParameters;
     var signingKey = parameters.IssuerSigningKeys.First();
     var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature);
     var header = new JwtHeader(signingCredentials);
     var payload = new JwtPayload {
         { JwtRegisteredClaimNames.UniqueName, UserName },
         { JwtRegisteredClaimNames.Iss, parameters.ValidIssuers.First() },
         { JwtRegisteredClaimNames.Aud, parameters.ValidAudiences },
         { JwtRegisteredClaimNames.Iat, DateTimeOffset.UtcNow.ToUnixTimeSeconds() },
         { JwtRegisteredClaimNames.Nbf, DateTimeOffset.UtcNow.ToUnixTimeSeconds() },
         { JwtRegisteredClaimNames.Exp, DateTimeOffset.UtcNow.AddMinutes(30).ToUnixTimeSeconds() }
     };
     var jwtSecurityToken = new JwtSecurityToken(header, payload);
     var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
     var token = jwtSecurityTokenHandler.WriteToken(jwtSecurityToken);
     return token;
 });
 

Perform verification

PS D:\Learn\MyJWT> curl.exe -i "http://localhost:5276/login?username=admin&password=1111"
 HTTP/1.1 200 OK
 Content-Type: text/plain; charset=utf-8
 Date: Mon, 04 Dec 2023 05:03:36 GMT
 Server: Kestrel
 Transfer-Encoding: chunked

 eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImFkbWluIiwiaXNzIjoiZG90bmV0LX VzZXItand0cyIsImF1ZCI6WyJodHRwOi8vbG9jYWxob3N0OjI5NzU0IiwiaHR0cHM6Ly9sb2NhbGhvc3Q6NDQzNjAiLCJodHRwOi8vbG9jYWxob3N0OjUyNzYiLCJodHRwczovL2xvY2FsaG9zd Do3MjUzIl0sImlhdCI6MTcwMTY2NjIxNiwibmJmIjoxNzAxNjY2MjE2LCJleHAiOjE3MDE2NjgwMTZ9.P9t7vIFfM7cddRPs4OQUTVVdo57nWTLt_ea2UynGUpo
 PS D:\Learn\MyJWT>
 PS D:\Learn\MyJWT>
 PS D:\Learn\MyJWT> curl.exe -i -H "Authorization: Bearer eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6 ImFkbWluIiwiaXNzIjoiZG90bmV0LXVzZXItand0cyIsImF1ZCI6WyJodHRwOi8vbG9jYWxob3N0OjI5NzU0IiwiaHR0cHM6Ly9sb2NhbGhvc3Q6NDQzNjAiLCJodHRwOi8vbG9jYWxob3N0 OjUyNzYiLCJodHRwczovL2xvY2FsaG9zdDo3MjUzIl0sImlhdCI6MTcwMTY2NjIxNiwibmJmIjoxNzAxNjY2MjE2LCJleHAiOjE3MDE2NjgwMTZ9.P9t7vIFfM7cddRPs4OQUTVVdo57nWTLt_ea2Uyn GUpo" http://localhost:5276/secret
 HTTP/1.1 200 OK
 Content-Type: text/plain; charset=utf-8
 Date: Mon, 04 Dec 2023 05:03:50 GMT
 Server: Kestrel
 Transfer-Encoding: chunked

 Hello admin. My secret
 
This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/811132

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索