Asp.net core 6 MVC RSA算法认证问题

问题描述 投票:0回答:0

我正在尝试在我的项目中集成 RSA 令牌生成

但是出现未经授权的错误。

可能是我在下面的代码中遗漏了一些东西

builder.Services.AddSingleton<RsaSecurityKey>(provider =>
{    
    string publicKey = System.IO.File.ReadAllText("D:\\wwwroot\\keys\\publickey.crt");
    publicKey = publicKey.Replace("-----BEGIN PUBLIC KEY-----\n", string.Empty);
    publicKey = publicKey.Replace("\n-----END PUBLIC KEY-----\n", string.Empty);
    
    System.Security.Cryptography.RSA rsa = System.Security.Cryptography.RSA.Create();
    rsa.ImportSubjectPublicKeyInfo(
        source: Convert.FromBase64String(publicKey),
        bytesRead: out int _
    );

    return new RsaSecurityKey(rsa);
});

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        SecurityKey rsa = builder.Services.BuildServiceProvider().GetRequiredService<RsaSecurityKey>();

        options.IncludeErrorDetails = true; // <- great for debugging

        // Configure the actual Bearer validation
        options.TokenValidationParameters = new TokenValidationParameters
        {
            IssuerSigningKey = rsa,
            //ValidAudience = "jwt-test",
            //ValidIssuer = "jwt-test",
            RequireSignedTokens = true,
            RequireExpirationTime = true, 
            ValidateLifetime = true, 
            ValidateAudience = true,
            ValidateIssuer = true,
        };
    });

我在 pragram.cs 文件中添加了上面的代码

请推荐

c# asp.net-mvc asp.net-core rsa
© www.soinside.com 2019 - 2024. All rights reserved.