From 0fb444db99d3a98b2f04449003ded00726ce914d Mon Sep 17 00:00:00 2001 From: hello Date: Tue, 12 Mar 2024 11:35:00 +0800 Subject: [PATCH] =?UTF-8?q?JWT=E8=BA=AB=E4=BB=BD=E8=AE=A4=E8=AF=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- notes/helloshop/jwt-bearer-authentication.md | 67 ++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 notes/helloshop/jwt-bearer-authentication.md diff --git a/notes/helloshop/jwt-bearer-authentication.md b/notes/helloshop/jwt-bearer-authentication.md new file mode 100644 index 0000000..bf8d382 --- /dev/null +++ b/notes/helloshop/jwt-bearer-authentication.md @@ -0,0 +1,67 @@ +# 使用 JwtBearer 令牌进行身份验证 + + +## 介绍 + +JwtBearer 令牌身份验证是一种基于 JSON Web 令牌的身份验证方法, 用于验证用户的身份, 它是一种无状态的身份验证方法, 适用于 Web API 和 Web 应用程序。 + + +## 安装 NuGet 包 + +```shell +dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer +``` + +## 自建 Identity Api 终结点 + +```csharp +builder.Services.AddIdentity(options => +{ + options.SignIn.RequireConfirmedAccount = false; + options.Password.RequireDigit = false; + options.Password.RequireLowercase = false; + options.Password.RequireUppercase = false; + options.Password.RequireNonAlphanumeric = false; + options.Password.RequiredLength = 5; +}).AddEntityFrameworkStores(); +``` + +## 使用 JwtBearer 验证令牌 + +```csharp + +builder.Services.AddAuthentication(options => +{ + options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultSignInScheme = CustomJwtBearerDefaults.AuthenticationScheme; +}).AddJwtBearer(options => +{ + options.TokenValidationParameters.ValidateIssuer = false; + options.TokenValidationParameters.ValidateAudience = false; + options.TokenValidationParameters.IssuerSigningKey = new SymmetricSecurityKey(Encoding.Default.GetBytes(issuerSigningKey)); + +}) +``` + +## 自定义身份认证处理程序 + +```csharp +public class CustomJwtBearerDefaults + +public class CustomJwtBearerOptions + +public class CustomJwtBearerHandler + +public class CustomJwtBearerExtensions +``` + +## 配置令牌生成 + +```csharp +builder.Services.AddAuthentication().AddJwtBearer().AddCustomJwtBearer(options => +{ + options.IssuerSigningKey = issuerSigningKey; + options.SecurityAlgorithm = SecurityAlgorithms.HmacSha256; +}); +``` \ No newline at end of file