尽管为安全端点分配了有效令牌,但邮递员仍返回401

时间:2019-12-09 19:05:13

标签: c# security asp.net-core .net-core jwt

我已经像下面这样建立了授权,松散地跟随着三个博客hereherehere(除了有效期的确认,基本上是公开的)

string secret = "super-secret-password";
byte[] bytes = Encoding.ASCII.GetBytes(secret);
SymmetricSecurityKey key = new SymmetricSecurityKey(bytes);
TokenValidationParameters parameters = new TokenValidationParameters
{
  IssuerSigningKey = key,
  ValidateLifetime = true,
  ValidateIssuerSigningKey = false,
  ValidateIssuer = false,
  ValidateAudience = false,
  RequireAudience = false,
  RequireExpirationTime = false,
  RequireSignedTokens = false
};
services.AddAuthentication(_ => _.DefaultScheme = JwtBearerDefaults.AuthenticationScheme)
  .AddJwtBearer(_ => _.TokenValidationParameters = parameters);

分配的令牌就是这样创建的。

string secret = "super-secret-password";
byte[] bytes = Encoding.ASCII.GetBytes(secret);
SymmetricSecurityKey key = new SymmetricSecurityKey(bytes);

Claim[] claims = {
  new Claim("role", "basic"),
  new Claim("role", "elevated"),
  new Claim("name", name)
};

JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
SecurityTokenDescriptor descriptor = new SecurityTokenDescriptor
{
  Subject = new ClaimsIdentity(claims),
  Expires = DateTime.Now.AddHours(1),
  SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature)
};

SecurityToken token = handler.CreateToken(descriptor);
return handler.WriteToken(token);

然后,我将返回的字符串粘贴到JWT.io中,并确认一切都很好(有效的签名等)。但是,当我在Postman中使用该令牌(它添加标头 Bearer + my_token_string )时,该呼叫给了我401未经授权的权限。

我在控制器中尝试了两种安全方法,并且尝试了一种打开方法(后者按预期工作)。

[HttpGet("open"), AllowAnonymous]
public ActionResult OpenResult() { return Ok("Open result accessed."); }
[HttpGet("secure"), Authorize]
public ActionResult SecureResult() { return Ok("Secure result accessed."); }
[HttpGet("elevated"), Authorize(Roles = "elevated")]
public ActionResult ElevatedResult() { return Ok("Elevated result accessed."); }

我不知道我可能会缺少什么。更糟糕的是,我不确定如何进一步调查。

这时我该怎么办?

This answer建议设置标题。 This answer与我的轻松案例无关,没有经过观众的验证。 This answer确实没有提供太多帮助。 (只需确保表明我已经做了自己的努力。)

1 个答案:

答案 0 :(得分:1)

要检查的一件事是Startup.cs中Configure中“ use”语句的顺序。如果在app.UseAuthentication()之前有app.UseAuthorization(),则将获得401s。这在之前吸引了我:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseCors("CorsPolicy");

        app.UseRouting();

        app.UseAuthentication(); //make sure this comes before app.UseAuthorization()
        app.UseAuthorization(); 
        app.UseHttpsRedirection();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapHub<NotificationHubService>("/notification");
        });
    }