gpt4 book ai didi

asp.net - token 处理程序无法将 token 转换为 jwt token

转载 作者:行者123 更新时间:2023-12-01 17:02:50 42 4
gpt4 key购买 nike

我正在尝试使用 JwtSecurityTokenHandler 将 token 字符串转换为 jwt token 。但它出现错误说

IDX12709: CanReadToken() returned false. JWT is not well formed: '[PII is hidden]'.\nThe token needs to be in JWS or JWE Compact Serialization Format. (JWS): 'EncodedHeader.EndcodedPayload.EncodedSignature'. (JWE): 'EncodedProtectedHeader.EncodedEncryptedKey.EncodedInitializationVector.EncodedCiphertext.EncodedAuthenticationTag'.

如何解决这个问题?

这是我的 token

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImFkbWluIiwibmJmIjoxNTUwNjM3NzcxLCJleHAiOjE1NTA2Mzg5NzEsImlhdCI6MTU1MDYzNzc3MX0.tUcoyoHgkrX3rDKl0cRLd9FwLtRprQpgYepMoiekixY

var tokenHandler = new JwtSecurityTokenHandler();
var jwtToken = tokenHandler.ReadToken(token) as JwtSecurityToken;

调用Web API

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);  

The above line works for System.IdentityModel.Tokens.Jwt package version 4.0.0. As @Nick commented, in the latest versions of the package, the JwtSecurityToken does not exist in the previous namespace anymore, instead it exists in System.IdentityModel.Tokens.Jwt so you need to write: var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(jwt);

除非您的 token 格式不正确。如果您也分享 token 会更好。

更新:

您还需要从 token 的开头删除单词“Bearer”(如果没有):

 var jwt = context.Request.Headers["Authorization"].Replace("Bearer ", string.Empty);

关于asp.net - token 处理程序无法将 token 转换为 jwt token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54778724/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com