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

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

问题描述

我已经设置了这样的授权,大致遵循三个博客此处这里here(除了验证过期时间外,基本上使其完全开放).

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

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

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