Asp.net-Core

JWT 令牌身份驗證失敗並顯示消息“PII 已隱藏”

  • June 19, 2020

在我的 .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:簽名驗證失敗。嘗試的鍵:'

‘。擷取的異常:’’。令牌:’’.

通過在 Startup 類的 Configure() 中添加以下內容,可以看到開發中隱藏的細節:

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

獲得完整消息後,請檢查所使用的密鑰對於令牌是否正確。

引用自:https://stackoverflow.com/questions/55300231