.net core 2.1基于令牌的身份验证给出401错误

时间:2020-08-15 20:02:42

标签: bearer-token core-api

您好,我正在使用基于令牌的身份验证来开发应用程序。

在startup.cs中添加了以下代码。

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(jwtBearerOptions =>
                {
                    jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidateActor = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer ="Issuer",
                        ValidAudience ="Audience",
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("ProEMLh5e_qnzdNUQrqdHPgp"))
                    };
                });

app.UseAuthentication();

在控制器中

    HttpPost("AdminLogin")]
    public IActionResult AdminLogin(Admin admin)
    {
       var result = admine.Login(admin);
       if (result!=null && result.Id>0)
       {
          var claims = new[]
          {
             new Claim(JwtRegisteredClaimNames.Sub, admin.Username),
             new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
          };
          var token = new JwtSecurityToken
          (
              issuer: "issuer", 
              audience: "Audience",
              claims: claims,
              expires: DateTime.UtcNow.AddDays(1), 
              notBefore: DateTime.UtcNow,
              signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes("ProEMLh5e_qnzdNUQrqdHPgp")),
              SecurityAlgorithms.HmacSha256)
              );
              result.Token = new JwtSecurityTokenHandler().WriteToken(token);            
       }
       return Ok(result);
   }

它可以工作并生成令牌并返回。我的问题是,当我发送带有此令牌的请求时。它给出401授权错误。低于一个

 [Authorize]
 [HttpPost("Exams")]
 public IActionResult Exams([FromBody] Exam model)
 {
   var result = exam.GEtExams(model.Id);
   return Ok(result);
 }

此图像用于生成代码try enter image description here

生成并返回后,我尝试了邮递员此令牌,例如 enter image description here

我在哪里失踪?

预先感谢

0 个答案:

没有答案