尽管为安全端点分配了有效令牌,但邮递员仍返回401 [英] Postman returns 401 despite the valid token distributed for a secure endpoint

查看:83
本文介绍了尽管为安全端点分配了有效令牌,但邮递员仍返回401的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经按照以下三个博客松散地设置了这样的授权

I've set up the authorization like this, loosely following the three blogs here, here and here (basically making it wide open except for the validation of the expiration time).

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);

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

The token distributed is created like this.

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.

Then, I paste the returned string into JWT.io and it confirms that everything is great (valid signature and all that). However, when I use that token in Postman (it adds the header Bearer + my_token_string), the call gives me 401 unauthorized.

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

I tried two secure methods in my controller and one open (the latter works as expected).

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

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

I don't know what I might be missing. Even worse, I'm not sure how to investigate it further.

这时我该怎么办?

此答案建议设置标题. 此答案与我的轻松案例无关没有观众的认可. 此答案确实没有提供太多帮助. (只需确保表明我已经做了自己的努力.)

This answer suggest setting headers. This answer is irrelevant for my relaxed case with no validation of audience. This answer gives nothing much, really. (Just making sure to show that I've done my effort.)

推荐答案

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

One thing to check is the ordering of "use" statements in Configure in Startup.cs. If you have app.UseAuthorization() before app.UseAuthentication() you'll get 401s. This has caught me before:

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

这篇关于尽管为安全端点分配了有效令牌,但邮递员仍返回401的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆