用从 OpenIddict 获取的 token 请求 api 时日志中出现如题的错误,请问如何解决?
2022-09-01 14:33:09.486 [Debug] The event "OpenIddict.Validation.OpenIddictValidationEvents+ProcessAuthenticationContext" was marked as rejected by "OpenIddict.Validation.OpenIddictValidationHandlers+ValidateIdentityModelToken".
/connect/authenticated
OpenIddict.Validation.OpenIddictValidationDispatcher
2022-09-01 14:33:09.499 [Information] "OpenIddict.Validation.AspNetCore" was not authenticated. Failure message: "An error occurred while authenticating the current request."
/connect/authenticated
将日志级别改为 Trace,拿到了进一步的日志信息
2022-09-01 15:10:23.967 [Verbose] An error occurred while validating the token '"****"'
OpenIddict.Validation.OpenIddictValidationDispatcher
Microsoft.IdentityModel.Tokens.SecurityTokenDecryptionFailedException: IDX10609: Decryption failed. No Keys tried: token: 'System.String'.
at Microsoft.IdentityModel.JsonWebTokens.JwtTokenUtilities.ValidateDecryption(JwtTokenDecryptionParameters decryptionParameters, Boolean decryptionSucceeded, Boolean algorithmNotSupportedByCryptoProvider, StringBuilder exceptionStrings, StringBuilder keysAttempted)
at Microsoft.IdentityModel.JsonWebTokens.JwtTokenUtilities.DecryptJwtToken(SecurityToken jwtToken, TokenValidationParameters validationParameters, JwtTokenDecryptionParameters decryptionParameters)
at Microsoft.IdentityModel.JsonWebTokens.JsonWebTokenHandler.DecryptToken(JsonWebToken jwtToken, TokenValidationParameters validationParameters)
at Microsoft.IdentityModel.JsonWebTokens.JsonWebTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters)
上面的错误是在 OpenIddictValidationHandlers.cs 中返回的
var result = context.Options.JsonWebTokenHandler.ValidateToken(context.Token, parameters);
参考 stackoverflow 上 OpenIddict Decryption of key failure 的回答解决了。
在 AddJwtBearer 中添加 OpenIddict 所使用的同样的证书
services.AddAuthentication()
.AddJwtBearer(
options =>
{
var cert = X509Certificate2.CreateFromPemFile("cnblogs.com.crt", "cnblogs.com.key");
options.TokenValidationParameters.TokenDecryptionKey =
new X509SecurityKey(cert);
});
OpenIddict 中添加证书的代码
var builder = services.AddOpenIddict()
.AddServer(options =>
{
var cert = X509Certificate2.CreateFromPemFile("cnblogs.com.crt", "cnblogs.com.key");
options.AddEncryptionCertificate(cert);
options.AddSigningCertificate(cert);
});
通过 How to properly validate OpenIddict JWT access_token in API? 找到了更好的解决方法,不需要设置在 AddJwtBearer 中设置,直接在 OpenIddict 的 AddValidation 中设置 AddEncryptionCertificate
var cert = X509Certificate2.CreateFromPemFile("cnblogs.com.crt", "cnblogs.com.key");
builder = services.AddOpenIddict()
.AddServer(options =>
{
options.AddEncryptionCertificate(cert);
options.AddSigningCertificate(cert);
})
.AddValidation(options =>
{
options.AddEncryptionCertificate(cert);
});