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

问题描述 投票:0回答:1

[我已经像这样设置了授权,松散地关注了三个博客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中,并确认一切都很好(有效的签名等)。但是,当我在邮递员中使用该令牌(它添加标头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没什么大不了的。 (只需确保表明我已经做了自己的努力。)

c# security asp.net-core .net-core jwt
1个回答
0
投票

要检查的一件事是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");
        });
    }
© www.soinside.com 2019 - 2024. All rights reserved.