使用 .NET Core 中的公共安全密钥配置 JWT Bearer 令牌验证 [英] Configure JWT Bearer token validation using the public security key in .NET Core

查看:23
本文介绍了使用 .NET Core 中的公共安全密钥配置 JWT Bearer 令牌验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Web 应用程序是某种 3rd 方服务的包装器.此 3rd 方服务使用 JWT Bearer 身份验证来访问其 WebAPI 端点.令牌采用 RS256 算法(非对称)加密.

My web application is a kind of wrapper for some 3rd party service. This 3rd party service uses the JWT Bearer authentication to access its WebAPI endpoints. The tokens are encrypted with RS256 algorithm (asymmetric).

我有一个公钥来验证我这边的令牌签名.在 jwt.io 站点上验证签名很容易(只需将令牌和公钥粘贴到文本框中即可).但是如何配置 TokenValidationParameters 以使用指定的公钥自动验证令牌?

I have a Public Key to validate tokens signature on my side. It is easy to validate signature on jwt.io site (just paste the token and public key to the text boxes). But how do I configure TokenValidationParameters to have tokens validated automatically using specified Public Key?

AddAuthentication 代码片段:

AddAuthentication code snippet:

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.TokenValidationParameters.ValidateIssuer = true;
    options.TokenValidationParameters.ValidIssuer = "iss";
    options.TokenValidationParameters.ValidateIssuerSigningKey = true;
    options.TokenValidationParameters.IssuerSigningKey = SomeCodeToGenerateSecurityKeyUsingPublicKeyOnly("-----BEGIN PUBLIC KEY-----...-----END PUBLIC KEY-----");
    options.TokenValidationParameters.ValidateAudience = false;
    options.TokenValidationParameters.ValidateLifetime = true;
    options.TokenValidationParameters.ClockSkew = TimeSpan.Zero;
});

services.AddAuthorization(options =>
{
    options.AddPolicy("Bearer",
        new AuthorizationPolicyBuilder(new string[] { JwtBearerDefaults.AuthenticationScheme })
            .RequireAuthenticatedUser()
            .Build()
    );
});

我不能像这样使用 SymmetricSecurityKey 类:

I can't just use SymmetricSecurityKey class like this:

options.TokenValidationParameters.IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("..."));

因为非对称加密.在这种情况下会发生异常:

because of asymmetric encryption. In this case an exception occurs:

IDX10503: Signature validation failed. Keys tried: 'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey , KeyId: 
'.
Exceptions caught:
 ''.
token: '{"alg":"RS256","typ":"JWT"}....

推荐答案

好的,最终我通过以下解决方案成功了.RsaSecurityKey 对象实现了我一直在寻找的技巧:

Okay, eventually I was succeeded with following solution. The RsaSecurityKey object do the trick I was looking for:

byte[] publicKeyBytes = Convert.FromBase64String("public_key_without_header_and_footer");
RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)PublicKeyFactory.CreateKey(publicKeyBytes);
RSAParameters rsaParameters = new RSAParameters
{
    Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned(),
    Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned(),
};

......

options.TokenValidationParameters.IssuerSigningKey = new RsaSecurityKey(rsaParameters);

我不确定这是否是最好的解决方案,但我暂时没有其他解决方案.

I'm not sure if this is the best solution, but I haven't some another one for now.

这篇关于使用 .NET Core 中的公共安全密钥配置 JWT Bearer 令牌验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆