【问题标题】:Configure JWT Bearer token validation using the public security key in .NET Core使用 .NET Core 中的公共安全密钥配置 JWT Bearer 令牌验证
【发布时间】:2018-09-15 11:04:23
【问题描述】:

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

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

添加验证码sn -p:

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 类:

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

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

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

【问题讨论】:

    标签: validation .net-core jwt bearer-token


    【解决方案1】:

    好的,最终我成功完成了以下解决方案。 RsaSecurityKey 对象可以满足我的要求:

    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);
    

    我不确定这是否是最好的解决方案,但我目前还没有其他解决方案。

    【讨论】:

    • 什么是 PublicKeyFactory?
    • PublicKeyFactory 位于 BouncyCastle.NetCore Nuget 包的 Org.BouncyCastle.Security 命名空间中。
    猜你喜欢
    • 2018-11-11
    • 1970-01-01
    • 2021-06-27
    • 2019-08-25
    • 2020-07-23
    • 2015-11-18
    • 1970-01-01
    • 2021-10-29
    • 2018-08-29
    相关资源
    最近更新 更多