2. 理解 JWT:結(jié)構(gòu)與工作原理


一個(gè)標(biāo)準(zhǔn)的 JWT 由三部分組成:

  1. Header(頭部):聲明簽名所用算法等元信息
  2. Payload(載荷):存放實(shí)際的聲明(Claims),如用戶名、Email、角色等
  3. Signature(簽名):對前兩部分進(jìn)行簽名,保障完整性

客戶端登錄后獲取到 JWT,每次請求將它放入 Authorization: Bearer < token > 頭,服務(wù)器驗(yàn)證簽名并提取聲明,實(shí)現(xiàn)無狀態(tài)鑒權(quán)。


3. 安裝必要的 NuGet 包?@1:16

在項(xiàng)目根目錄執(zhí)行或通過 VS Code、自帶終端安裝:

dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore  
dotnet add package Microsoft.EntityFrameworkCore.SqlServer  
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer  

4. 擴(kuò)展應(yīng)用用戶模型(AppUser)

新建 Models/AppUser.cs,繼承內(nèi)置 IdentityUser,便于后續(xù)擴(kuò)展自定義字段:

public class AppUser : IdentityUser
{
    // 可根據(jù)業(yè)務(wù)需求添加更多屬性
    // public int RiskLevel { get; set; }
}

5. 配置應(yīng)用 DbContext 使用 Identity

修改 Data/AppDbContext.cs,繼承自 IdentityDbContext < AppUser > 而非普通 DbContext

public class AppDbContext : IdentityDbContext < AppUser >
{
    public AppDbContext(DbContextOptions < AppDbContext > options)
        : base(options) { }

    // 其他 DbSet < TEntity > …
}

6. 在 Program.cs 中注冊 Identity 與 JWT

6.1 添加 Identity 服務(wù)與密碼策略

builder.Services.AddIdentity < AppUser, IdentityRole > (options = >
{
    options.Password.RequireDigit           = true;
    options.Password.RequireLowercase       = true;
    options.Password.RequireUppercase       = true;
    options.Password.RequireNonAlphanumeric = true;
    options.Password.RequiredLength         = 12;
})
.AddEntityFrameworkStores < AppDbContext > ()
.AddDefaultTokenProviders();

6.2 添加 EF Core 存儲(chǔ)

同上 .AddEntityFrameworkStores < AppDbContext > () 已將 AppDbContext 注入 Identity。

6.3 配置 JWT 驗(yàn)證方案

先在 appsettings.json 中增加配置段:

"Jwt": {
  "Issuer":   "https://localhost:5246",
  "Audience": "https://localhost:5246",
  "Key":      "請?zhí)鎿Q為至少512位以上的高強(qiáng)度隨機(jī)密鑰"
}

然后在 Program.cs 中:

var jwtSettings = builder.Configuration.GetSection("Jwt");
var key = Encoding.UTF8.GetBytes(jwtSettings["Key"]);

builder.Services
    .AddAuthentication(options = >
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options = >
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer           = true,
            ValidIssuer              = jwtSettings["Issuer"],
            ValidateAudience         = true,
            ValidAudience            = jwtSettings["Audience"],
            ValidateIssuerSigningKey = true,
            IssuerSigningKey         = new SymmetricSecurityKey(key)
        };
    });

6.4 啟用中間件

app.UseAuthentication();
app.UseAuthorization();

7. 通過 EF Core 遷移生成表結(jié)構(gòu)

在終端運(yùn)行:

dotnet ef migrations add AddIdentity
dotnet ef database update

8. 驗(yàn)證結(jié)果:檢查數(shù)據(jù)庫表

使用 SQL Server Management Studio 或其他工具,可見生成了以下表:


9. 小結(jié)與最佳實(shí)踐

通過以上步驟,你已完成 ASP.NET Core 中 Identity 與 JWT 的完整集成,具備生產(chǎn)級別的用戶認(rèn)證能力。祝你開發(fā)順利!

原文引自YouTube視頻:https://www.youtube.com/watch?v=Pkeu_o8k99Q

上一篇:

.NET Core Web API 開發(fā)入門:環(huán)境搭建與項(xiàng)目初始化實(shí)戰(zhàn)

下一篇:

使用 Node.js 和 Express 構(gòu)建 REST API:完整教程
#你可能也喜歡這些API文章!

我們有何不同?

API服務(wù)商零注冊

多API并行試用

數(shù)據(jù)驅(qū)動(dòng)選型,提升決策效率

查看全部API→
??

熱門場景實(shí)測,選對API

#AI文本生成大模型API

對比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個(gè)渠道
一鍵對比試用API 限時(shí)免費(fèi)

#AI深度推理大模型API

對比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個(gè)渠道
一鍵對比試用API 限時(shí)免費(fèi)