首页 > 解决方案 > JWT 令牌身份验证失败并显示消息“PII 已隐藏”

问题描述

在我的 .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)
                };
            });

在控制器上我有这个代码:

    [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!");
    }

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

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

标签: asp.net-core.net-corejwt

解决方案


通过在 Startup 类的 Configure() 中添加以下内容,可以看到开发中隐藏的细节:

if (env.IsDevelopment())
{
     IdentityModelEventSource.ShowPII = true; 
}

获得完整消息后,请检查所使用的密钥对于令牌是否正确。


推荐阅读