我已经在Apigee中创建了一个代理来生成JWT令牌。我已经在Apigee中创建了另一个代理来验证JWT令牌,并且我能够使用它进行验证。现在,我无法从.NET/C#代码中完全验证JWT令牌。
下面是我尝试过的.NET代码:
private static bool ValidateToken(string authToken, string key)
{
var tokenHandler = new JwtSecurityTokenHandler();
var validationParameters = GetValidationParameters(key);
SecurityToken validatedToken;
IPrincipal principal = tokenHandler.ValidateToken(authToken, validationParameters, out validatedToken);
return true;
}
private static TokenValidationParameters GetValidationParameters(string key)
{
return new TokenValidationParameters()
{
ValidateLifetime = false, // Because there is no expiration in the generated token
ValidateAudience = false, // Because there is no audiance in the generated token
ValidateIssuer = false, // Because there is no issuer in the generated token
ValidIssuer = "urn:apigee-edge-JWT-policy-test",
ValidAudience = "audience1",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("key")) // The same key as the one that generate the token
};
}以及JWT生成策略代码:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<GenerateJWT async="false" continueOnError="false" enabled="true" name="Generate-JWT-1">
<DisplayName>Generate JWT-1</DisplayName>
<Algorithm>HS256</Algorithm>
<SecretKey>
<Value ref="private.key"/>
</SecretKey>
<Subject>subject-subject</Subject>
<Issuer>urn://apigee-edge-JWT-policy-test</Issuer>
<Audience>audience1,audience2</Audience>
<ExpiresIn>8h</ExpiresIn>
<AdditionalClaims>
<Claim name="userId" type="string" ref="request.formparam.username"/>
</AdditionalClaims>
<OutputVariable>jwt-variable</OutputVariable>
</GenerateJWT>以下是错误消息:
Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException: IDX10503:签名验证失败。尝试键:'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey,KeyId:'',InternalId:'96edcecb-17ad-4022-a50b-558f426ed337‘。、KeyId:‘捕获的异常:'System.ArgumentOutOfRangeException: IDX10603:解密失败。密钥尝试:‘HS256 256’。捕获的例外情况:'128‘令牌:'96‘参数名称: Microsoft.IdentityModel.Tokens.SymmetricSignatureProvider..ctor(SecurityKey键处的KeySize,Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateSignatureProvider(SecurityKey键处的String算法,布尔willCreateSignatures),Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForVerifying(SecurityKey键处的字符串算法,Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForVerifying(SecurityKey键处的字符串算法,System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(Byte[] encodedBytes处的字符串算法,Byte[]签名,SecurityKey密钥,字符串算法,System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(String令牌,TokenValidationParameters validationParameters)‘.
发布于 2019-08-07 08:12:47
IssuerSigningKey =新的IssuerSigningKey
在上面的代码中,"key“值的大小小于预期。
https://stackoverflow.com/questions/57387255
复制相似问题