令牌处理程序无法将令牌转换为 jwt 令牌
Token handler unable to convert the token to jwt token
我正在尝试使用 JwtSecurityTokenHandler
将我的令牌字符串转换为 jwt 令牌。但是说
会出错
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'.
我该如何解决这个问题?
这是我的代币
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImFkbWluIiwibmJmIjoxNTUwNjM3NzcxLCJleHAiOjE1NTA2Mzg5NzEsImlhdCI6MTU1MDYzNzc3MX0.tUcoyoHgkrX3rDKl0cRLd9FwLtRprQpgYepMoiekixY
var tokenHandler = new JwtSecurityTokenHandler();
var jwtToken = tokenHandler.ReadToken(token) as JwtSecurityToken;
调用网络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就更好了
更新:
您还需要从标记的开头删除单词 "Bearer "(如果您没有):
var jwt = context.Request.Headers["Authorization"].Replace("Bearer ", string.Empty);
版本 5.6.0.0 - 目前是最新版本
可以使用与@thilim9 的问题类似的代码。
var tokenId = identity.Claims.SingleOrDefault(c => c.Type == "id_token")?.Value;
var handler = new JwtSecurityTokenHandler();
JwtSecurityToken token = handler.ReadJwtToken(tokenId);
对于 .net framework 4.5.1,我在生成令牌时删除了我的自定义密钥,并在 JwtRegisteredClaimNames
的声明中使用了默认值。
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.GivenName, Data.UserName),
new Claim(JwtRegisteredClaimNames.Prn,Data.Password),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
我正在尝试使用 JwtSecurityTokenHandler
将我的令牌字符串转换为 jwt 令牌。但是说
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'.
我该如何解决这个问题?
这是我的代币
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImFkbWluIiwibmJmIjoxNTUwNjM3NzcxLCJleHAiOjE1NTA2Mzg5NzEsImlhdCI6MTU1MDYzNzc3MX0.tUcoyoHgkrX3rDKl0cRLd9FwLtRprQpgYepMoiekixY
var tokenHandler = new JwtSecurityTokenHandler();
var jwtToken = tokenHandler.ReadToken(token) as JwtSecurityToken;
调用网络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 version4.0.0
. As @Nick commented, in the latest versions of the package, theJwtSecurityToken
does not exist in the previous namespace anymore, instead it exists inSystem.IdentityModel.Tokens.Jwt
so you need to write:var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(jwt);
除非您的令牌格式不正确。如果你也分享token就更好了
更新:
您还需要从标记的开头删除单词 "Bearer "(如果您没有):
var jwt = context.Request.Headers["Authorization"].Replace("Bearer ", string.Empty);
版本 5.6.0.0 - 目前是最新版本 可以使用与@thilim9 的问题类似的代码。
var tokenId = identity.Claims.SingleOrDefault(c => c.Type == "id_token")?.Value;
var handler = new JwtSecurityTokenHandler();
JwtSecurityToken token = handler.ReadJwtToken(tokenId);
对于 .net framework 4.5.1,我在生成令牌时删除了我的自定义密钥,并在 JwtRegisteredClaimNames
的声明中使用了默认值。
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.GivenName, Data.UserName),
new Claim(JwtRegisteredClaimNames.Prn,Data.Password),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};