JWT(JSON Web Token)是一種廣泛使用的身份驗證和授權方法。它通常用於傳輸用戶訊息,可以使用HMAC 演算法或 RSA 公鑰/私鑰對進行簽署。
我們預計將天氣預報資訊,設為需要進行驗證,才能讀取。
Bearer <token>
。Microsoft.AspNetCore.Authentication.JwtBearer
在 appsettings.json
中,設置 Issuer 和 Key
"JwtSettings": {
"Issuer": "Solution1",
"SecretKey": "ZG0JZtDY3^FnkbCYy@!vJfVE922k9MJG"
}
在 Program.cs
設定驗證,並讀取 JwtSettings 設定
using Microsoft.AspNetCore.Authentication.JwtBearer;
// 讀取 JwtSettings
builder.Services.Configure<JwtSettings>(builder.Configuration.GetSection("JwtSettings"));
// 啟用 JwtBearer 驗證
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
// 驗證 Issuer
ValidateIssuer = true,
ValidIssuer = builder.Configuration.GetValue<string>("JwtSettings:Issuer"),
ValidateAudience = true, // 啟用受眾驗證
ValidAudience = "yourdomain.com", // 設置預期的受眾
// 驗證 Token 有效期間
ValidateLifetime = true,
// 驗證 SecurityKey
ValidateIssuerSigningKey = true,
// Key
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration.GetValue<string>("JwtSettings:SecretKey")))
};
});
// 順序不能錯,先驗證再授權
app.UseAuthentication();
app.UseAuthorization();
<aside>
💡 ValidateAudience
的作用(2024/07/16補充)
當 ValidateAudience
設置為 true
時,JWT 驗證過程會檢查令牌中的 aud
聲明,確保它與 TokenValidationParameters
中指定的預期受眾匹配。如果 aud
不匹配,令牌驗證將失敗,並且身份驗證過程會被拒絕。
為什麼需要 ValidateAudience
?