簡體   English   中英

使用.NET Core中的公共安全密鑰配置JWT Bearer令牌驗證

[英]Configure JWT Bearer token validation using the public security key in .NET Core

我的Web應用程序是一種第三方服務的包裝器。 此第三方服務使用JWT承載身份驗證來訪問其WebAPI端點。 令牌用RS256算法加密(不對稱)。

我有一個公鑰來驗證我身邊的令牌簽名。 在jwt.io站點上驗證簽名很容易(只需將令牌和公鑰粘貼到文本框中)。 但是,如何配置TokenValidationParameters以使用指定的公鑰自動驗證令牌?

AddAuthentication代碼段:

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"}....

好吧,最終我成功完成了以下解決方案。 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);

我不確定這是否是最好的解決方案,但我現在還沒有其他的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM