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

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

问题描述

我的Web应用程序是某种第三方服务的包装.此第三方服务使用JWT承载身份验证来访问其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天全站免登陆