gpt4 book ai didi

c# - 如何使用.Net Core验证KeyCloak提供的JWT?

转载 作者:行者123 更新时间:2023-12-05 06:04:51 27 4
gpt4 key购买 nike

我有一个 ASP.Net Core 5 资源服务器,我想验证我的访问 token 但尚未成功。

我写了一个中间件来更好地处理错误:

var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_configuration["Jwt:Kid"]); // Kid is copied from 'openid-connect/certs'

tokenHandler.ValidateToken(token, new TokenValidationParameters
{
ValidIssuer = _configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateAudience = false,
ValidateIssuer = true,
ValidateIssuerSigningKey = true,
ValidateLifetime = false
}, out SecurityToken validatedToken);

我的 KeyCloak 的 key 在 */auth/realms/test/protocol/openid-connect/certs 上:

{
"keys": [
{
"kid": "O9cbi7dzidpxZGLV2eXlTvIECoKDB_YbUN2m73rp8",
"kty": "RSA",
"alg": "RS256",
"use": "sig",
"n": "qMaFN3tmQ0TaGWaWcanebanGDgh_bz7RzlTbbkiGtY707x...hF40ofv1Fxoy7hBUEKARUqCgjltj5_0TtWn850Eqak41lpa-P_PNsGdwBf18mqBCT8pFbzs8DeRZaD1Q",
"e": "AQAB",
"x5c": [
"MIIClzCCAX8CBgF3jSSr9TANBgkqhkiG9w0BAQsFADAPMQ0wCwYDVQQDDAR0ZXN0MB4XDTIxMDIxMDE4MTAyNloXDTMxMDIxMDE4MTIwNlowDzENMAsGA1UEAwwEdGVzdDCCASIwDQYJKoZI...8tUe5h/7rg1+bHAGVbWg=="
],
"x5t": "G5NYmhm8yEwqHtyLwygxGw89A",
"x5t#S256": "nEnZWkJQyCG4czEJx04Nyszyzc3l8bsxZ3es2wDTw"
}
]
}

发出请求时,我总是会遇到以下异常。

{"IDX10501: Signature validation failed. Unable to match key: \nkid: 'System.String'.\nExceptions caught:\n 'System.Text.StringBuilder'. \ntoken: 'System.IdentityModel.Tokens.Jwt.JwtSecurityToken'."}

知道我做错了什么吗?

最佳答案

RSA 不是对称算法。所以不要使用 SymmetricSecurityKey 作为签名 key 使用 JsonWebKey 来自动为你生成正确的 key :

tokenHandler.ValidateToken(token, new TokenValidationParameters
{
ValidIssuer = _configuration["Jwt:Issuer"],
IssuerSigningKey = new JsonWebKey(jsonKeyString),
ValidateAudience = false,
ValidateIssuer = true,
ValidateIssuerSigningKey = true,
ValidateLifetime = false
}, out SecurityToken validatedToken);

其中 jsonKeySting 是一个字符串变量,它在提到的 json 中保存您的关键段

{
"kid": "O9cbi7dzidpxZGLV2eXlTvIECoKDB_YbUN2m73rp8",
"kty": "RSA",
"alg": "RS256",
"use": "sig",
"n": "qMaFN3tmQ0TaGWaWcanebanGDgh_bz7RzlTbbkiGtY707x...hF40ofv1Fxoy7hBUEKARUqCgjltj5_0TtWn850Eqak41lpa-P_PNsGdwBf18mqBCT8pFbzs8DeRZaD1Q",
"e": "AQAB",
"x5c": [
"MIIClzCCAX8CBgF3jSSr9TANBgkqhkiG9w0BAQsFADAPMQ0wCwYDVQQDDAR0ZXN0MB4XDTIxMDIxMDE4MTAyNloXDTMxMDIxMDE4MTIwNlowDzENMAsGA1UEAwwEdGVzdDCCASIwDQYJKoZI...8tUe5h/7rg1+bHAGVbWg=="
],
"x5t": "G5NYmhm8yEwqHtyLwygxGw89A",
"x5t#S256": "nEnZWkJQyCG4czEJx04Nyszyzc3l8bsxZ3es2wDTw"
}

关于c# - 如何使用.Net Core验证KeyCloak提供的JWT?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66188221/

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