
一步步教你進(jìn)行 Python REST API 身份驗(yàn)證
一個(gè)標(biāo)準(zhǔn)的 JWT 由三部分組成:
客戶端登錄后獲取到 JWT,每次請求將它放入 Authorization: Bearer < token >
頭,服務(wù)器驗(yàn)證簽名并提取聲明,實(shí)現(xiàn)無狀態(tài)鑒權(quán)。
在項(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
新建 Models/AppUser.cs
,繼承內(nèi)置 IdentityUser
,便于后續(xù)擴(kuò)展自定義字段:
public class AppUser : IdentityUser
{
// 可根據(jù)業(yè)務(wù)需求添加更多屬性
// public int RiskLevel { get; set; }
}
修改 Data/AppDbContext.cs
,繼承自 IdentityDbContext < AppUser >
而非普通 DbContext
:
public class AppDbContext : IdentityDbContext < AppUser >
{
public AppDbContext(DbContextOptions < AppDbContext > options)
: base(options) { }
// 其他 DbSet < TEntity > …
}
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();
同上 .AddEntityFrameworkStores < AppDbContext > ()
已將 AppDbContext
注入 Identity。
先在 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)
};
});
app.UseAuthentication();
app.UseAuthorization();
在終端運(yùn)行:
dotnet ef migrations add AddIdentity
dotnet ef database update
使用 SQL Server Management Studio 或其他工具,可見生成了以下表:
Jwt:Key
必須為高強(qiáng)度隨機(jī)值,切勿硬編碼或泄露。IdentityOptions.Password
,平衡易用與安全。通過以上步驟,你已完成 ASP.NET Core 中 Identity 與 JWT 的完整集成,具備生產(chǎn)級別的用戶認(rèn)證能力。祝你開發(fā)順利!
原文引自YouTube視頻:https://www.youtube.com/watch?v=Pkeu_o8k99Q