令牌處理程序無法將令牌轉換為 jwt 令牌
我正在嘗試使用將我的令牌字元串轉換為 jwt 令牌
JwtSecurityTokenHandler。但它的說法是錯誤的IDX12709:CanReadToken() 返回錯誤。JWT 格式不正確:'
$$ PII is hidden $$’.\n令牌需要採用 JWS 或 JWE 緊湊序列化格式。(JWS):‘EncodedHeader.EndcodedPayload.EncodedSignature’。(JWE):‘EncodedProtectedHeader.EncodedEncryptedKey.EncodedInitializationVector.EncodedCiphertext.EncodedAuthenticationTag’。
我該如何解決這個問題?
這是我的令牌
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImFkbWluIiwibmJmIjoxNTUwNjM3NzcxLCJleHAiOjE1NTA2Mzg5NzEsImlhdCI6MTU1MDYzNzc3MX0.tUcoyoHgkrX3RxTkdkdk
var tokenHandler = new JwtSecurityTokenHandler(); var jwtToken = tokenHandler.ReadToken(token) as JwtSecurityToken;呼叫網路介面
using (HttpClient client = new HttpClient()) { string path = "UserMaintenance/ValidateUserId?userid=" + txtUsername.Text.Trim().ToString(); client.BaseAddress = new Uri(GlobalData.BaseUri); client.DefaultRequestHeaders.Add("Authorization", "Bearer" + GlobalData.Token); HttpResponseMessage response = client.GetAsync(path).Result; if (response.IsSuccessStatusCode) { var value = response.Content.ReadAsStringAsync().Result; isValid = JsonConvert.DeserializeObject<bool>(value); } }這是我的 GetPrincipal 方法
public static ClaimsPrincipal GetPrincipal(string token) { try { var symmetricKey = Convert.FromBase64String(Secret); var validationParameters = new TokenValidationParameters() { RequireExpirationTime = true, ValidateIssuer = false, ValidateAudience = false, IssuerSigningKey = new SymmetricSecurityKey(symmetricKey) }; var handler = new JwtSecurityTokenHandler(); handler.InboundClaimTypeMap.Clear(); SecurityToken securityToken; var principal = handler.ValidateToken(token, validationParameters, out securityToken); return principal; } catch (Exception ex) { return null; } }
我就是這樣做的,它對我有用:
var token = new System.IdentityModel.Tokens.JwtSecurityToken(jwt);上面的行適用於
System.IdentityModel.Tokens.Jwt包版本4.0.0。正如@Nick 評論的那樣,在最新版本的包JwtSecurityToken中,以前的命名空間中不再存在,而是存在,System.IdentityModel.Tokens.Jwt因此您需要編寫:var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(jwt);除非您的令牌格式不正確。如果您也共享令牌會更好。
更新:
您還需要從令牌的開頭刪除單詞**“Bearer”**(如果沒有):
var jwt = context.Request.Headers["Authorization"].Replace("Bearer ", string.Empty);