我實作了一個 Github 專案,不明白 Jwt 的用戶和關鍵系統是如何作業的。我現在有一個位于 AppSettings 中的密鑰,當用戶登錄時,將執行以下功能:
private string GenerateJwtToken(string username)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_appSettings.token);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[] { new Claim("username", username) }), //<-
Expires = DateTime.UtcNow.AddMinutes(30),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
因此,如果我做對了,那么我會在此處為登錄用戶生成令牌,但是用戶名所在的行是什么意思?之后,我將用戶名和令牌存盤在其中sessionStorage,如果我觸發了其他定義屬性的Controller地方[Authorize],我添加了跟隨的 Header 和 fetch:
headers: {
'Content-type': 'application/json',
'Authorization': `Bearer ${sessionStorage.getItem("token")}`,
},
然后它首先運行到這個函式:
public async Task Invoke(HttpContext context, IAuthService authService)
{
var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
if (token != null)
attachUserToContext(context, authService, token);
await _next(context);
}
private void attachUserToContext(HttpContext context, IAuthService authService, string token)
{
try
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
tokenHandler.ValidateToken(token, new TokenValidationParameters //<- Error
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false,
ClockSkew = TimeSpan.Zero
}, out SecurityToken validatedToken);
var jwtToken = (JwtSecurityToken)validatedToken;
var userId = int.Parse(jwtToken.Claims.First(x => x.Type == "username").Value);
context.Items["User"] = "user";
}
catch
{
// do nothing if jwt validation fails
// user is not attached to context so request won't have access to secure routes
}
}
所以在這里它驗證tokenfromHeader不為空,然后它嘗試做什么!?另外為什么這里又使用了用戶名?
當它運行該ValidateToken函式時,它回傳一個錯誤:IDX12709: CanReadToken() 回傳 false。JWT 格式不正確:'['System.String' 型別的 PII 被隱藏
https://github.com/cornflourblue/dotnet-5-jwt-authentication-api/tree/279c8058669bbfa59902a4473f62e5371167340c
uj5u.com熱心網友回復:
JWT 分為三個部分。第一個是帶有加密演算法等資訊的標頭。第二部分是有效負載,您實際上可以在其中找到您的宣告,在您的情況下,它將是一個用戶名,exp date,您可以在此處添加任何您需要的內容。此處添加了唯一的用戶名或 ID,以便服務器知道此令牌屬于誰以及誰正在呼叫服務器。在其他情況下,您將如何確定誰在呼叫服務器,您必須將此令牌保存在某個資料庫中或分配給用戶的某個地方。最后一部分是簽名,這部分是用你的密鑰驗證的,以知道它不是一些假令牌,而是你創建的一個令牌。部分由點分割。
很難說為什么您的令牌驗證失敗,首先我會嘗試在https://jwt.io上檢查您創建的令牌,看看里面有什么。也許您使用不記名前綴驗證令牌,因為它被寫入令牌形成錯誤,所以它可能是問題。
還有一件事,而不是使用自定義中間件身份驗證,您可以使用 JWT 默認身份驗證方案
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = false,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
.GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
//...
};
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/422479.html
標籤:
上一篇:C#如何檢查重疊范圍?
