當前位置: 妍妍網 > 碼農

ASP.NET Core 實戰:基於 JWT Token 的許可權控制全揭露

2024-03-25碼農

在現代Web應用程式中,許可權控制是確保套用安全性和使用者體驗的重要一環。ASP.NET Core 是一個強大的Web框架,它支持多種認證和授權機制。其中,基於JSON Web Tokens(JWT)的許可權控制是一種流行的解決方案。JWT提供了一種安全、可驗證的方式來傳遞使用者資訊,從而實作無狀態的認證和授權。

本文將詳細探討如何在ASP.NET Core中實施基於JWT Token的許可權控制,並提供程式碼範例來指導讀者實作。

一、JWT基本原理

JWT是一個開放標準(RFC 7519),它定義了一種緊湊的、自包含的方式,用於作為JSON物件在各方之間安全地傳輸資訊。這些資訊可以被驗證和信任,因為它們是數位簽名的。JWT通常用於在使用者和伺服器之間安全地傳輸資訊。一個JWT通常包含三個部份:Header(頭部)、Payload(負載)和Signature(簽名)。

在許可權控制場景中,伺服器在認證使用者後會生成一個JWT,並將其發送給客戶端。客戶端在後續的請求中會將JWT包含在請求頭中發送給伺服器。伺服器透過驗證JWT的有效性來確認使用者的身份和許可權。

二、ASP.NET Core中JWT許可權控制的實作

1. 安裝依賴包

首先,你需要在計畫中安裝JWT相關的依賴包。在ASP.NET Core計畫中,你可以使用NuGet包管理器來安裝 Microsoft.AspNetCore.Authentication.JwtBearer 包。

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

2. 配置JWT認證

Startup.cs 檔中的 ConfigureServices 方法中,你需要配置JWT認證服務。這包括指定JWT的簽發者、受眾、金鑰等資訊,並添加JWT Bearer認證中介軟體。

publicvoidConfigureServices(IServiceCollection services)
{
// 其他服務配置...
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "YourIssuer"// 替換為你的Issuer
ValidAudience = "YourAudience"// 替換為你的Audience
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSecurityKey")) // 替換為你的金鑰
};
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = tokenValidationParameters;
options.SaveToken = true;
});
// 添加授權策略(如果需要)
services.AddAuthorization(options =>
{
// 定義策略
options.AddPolicy("YourPolicy", policy =>
{
policy.RequireClaim("permission""your_permission_value"); // 根據需求添加Claim驗證
});
});
}

3. 套用認證和授權中介軟體

Configure 方法中,你需要確保認證和授權中介軟體被添加到管道中。

publicvoidConfigure(IApplicationBuilder app, IWebHostEnvironment env)
{
// 其他中介軟體配置...
app.UseAuthentication(); // 啟用認證中介軟體
app.UseAuthorization(); // 啟用授權中介軟體
// 其他中介軟體配置...
}

4. 生成JWT Token

在使用者登入成功後,你需要生成一個JWT Token並返回給客戶端。你可以使用 JwtSecurityToken JwtSecurityTokenHandler 類來生成JWT。

using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
publicstringGenerateJwtToken(string userId, string userName, string[] roles)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes("YourSecurityKey"); // 替換為你的金鑰
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, userName),
new Claim(ClaimTypes.NameIdentifier, userId),
// 添加其他自訂Claim,如許可權等
}),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(