.net core 2.2 jwt令牌身份验证失败,并显示“ PII隐藏”

aum*_*joa 3 jwt .net-core asp.net-core

在我的.net core 2.2微服务中,我尝试从JWT令牌中提取声明以进行一些授权。身份验证是在系统的另一部分上完成的,因此我现在不需要这样做。

我在Startup.cs中使用以下代码:

  services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                var signingKey = Encoding.UTF8.GetBytes("SECRET_KEY");
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    IssuerSigningKey = new SymmetricSecurityKey(signingKey)
                };
            });
Run Code Online (Sandbox Code Playgroud)

在控制器上,我有以下代码:

    [Authorize]
    [HttpPost]
    public async Task<ActionResult<CreateResponse>> Create()
    {
        var userIdClaim = HttpContext.User.Claims.Where(x => x.Type == "empId").SingleOrDefault();
        return Ok($"Your User ID is {userIdClaim.Value} and you can create invoices!");
    }
Run Code Online (Sandbox Code Playgroud)

我总是收到此错误消息和“未经授权”的响应:

Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException:IDX10503:签名验证失败。尝试过的键:“ [PII隐藏]”。捕获到异常:“ [PII隐藏]”。令牌:“ [PII隐藏]”。

use*_*816 12

You can see the hidden details in development by adding the following to Configure() in the Startup class:

if (env.IsDevelopment())
{
     IdentityModelEventSource.ShowPII = true; 
}
Run Code Online (Sandbox Code Playgroud)

Once you have the full message check the key being used is correct for the token.

  • 我可以确认这也适用于 2.2,同时确保您有``using Microsoft.IdentityModel.Logging;``` (4认同)