
一步步教你進行 Python REST API 身份驗證
要點:使用 Claims 可將用戶身份信息緩存于令牌中,每次請求僅需解析 JWT 即可獲取,無需再查 DB,極大提升響應速度。
/Interfaces
ITokenService.cs
/Services
TokenService.cs
/DTOs
RegisterResponseDto.cs
/Settings
appsettings.json
/Controllers
AccountController.cs
Program.cs
首先在 Interfaces/ITokenService.cs
中定義令牌生成約定:
public interface ITokenService
{
string CreateToken(AppUser user);
}
在 Services/TokenService.cs
中實現上述接口:
public class TokenService : ITokenService
{
private readonly IConfiguration _config;
private readonly SymmetricSecurityKey _key;
public TokenService(IConfiguration config)
{
_config = config;
// 5.1 從配置讀取簽名密鑰
_key = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
}
public string CreateToken(AppUser user)
{
// 5.2 構造 Claims 列表
var claims = new List < Claim >
{
new Claim(JwtRegisteredClaimNames.Email, user.Email),
new Claim(JwtRegisteredClaimNames.GivenName, user.UserName)
// 可根據需求加入更多自定義聲明
};
// 5.3 創建簽名憑證與 SecurityTokenDescripto
var creds = new SigningCredentials(
_key, SecurityAlgorithms.HmacSha512Signature);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.UtcNow.AddHours(1),
SigningCredentials = creds,
Issuer = _config["Jwt:Issuer"],
Audience = _config["Jwt:Audience"]
};
// 5.4 生成并序列化 JWT
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
}
// appsettings.json
"Jwt": {
"Key": "這里填入至少 512 位的隨機字符串",
"Issuer": "YourApp",
"Audience": "YourAppUsers"
}
builder.Services.AddScoped < ITokenService, TokenService > ();
// 同時需配置 Authentication 和 JwtBearer,省略此處
在 AccountController
的注冊方法中,使用 DTO 返回用戶名、郵箱及生成的令牌:
[HttpPost("register")]
public async Task < ActionResult < RegisterResponseDto>> Register(RegisterDto dto)
{
var user = new AppUser { UserName = dto.Username, Email = dto.Email };
// … 用戶創建邏輯
var token = _tokenService.CreateToken(user);
var response = new RegisterResponseDto
{
Username = user.UserName,
Email = user.Email,
Token = token
};
return Ok(response);
}
截圖?@15:35–15:44
POST /api/account/register
,填寫用戶名、郵箱和密碼;Token
字段;Token
粘貼至 jwt.io 等在線工具,驗證 Claims、Issuer、Audience 與簽名均符合預期。appsettings.json
外妥善保存簽名密鑰,切勿硬編碼或泄露。通過本文示例,你已掌握 ASP.NET Core 自定義 JWT 生成的核心流程,能夠在項目中快速集成高效、安全的令牌認證機制。祝編碼愉快!
原文引自YouTube視頻:https://www.youtube.com/watch?v=lZu9XcZit2Y