【问题标题】:How to fix always returning unathorized status of using [Authorize(Roles = "Manager")]?如何解决始终返回使用 [Authorize(Roles = "Manager")] 的未经授权状态?
【发布时间】:2019-06-17 18:31:26
【问题描述】:

我正在为 asp.net core webapi 实现基于角色的身份验证。我几乎遵循了这个教程。 https://medium.com/@engr.mmohsin/asp-net-core-2-0-webapi-jwt-role-based-authentication-authorization-with-custom-tables-and-identity-401c898d9ef1

我用管理账户[Authorize(Roles = "Manager")]登录后总是未经授权返回。

在控制器类中

[Route("api/[controller]")]
[Authorize(Roles = "Manager")]

在服务类的登录方法中生成令牌

var claims = new[] {

    new Claim("Name", user.Name), 
    //few other claims
    new Claim(ClaimTypes.Role, user.Role.ToString())


        };
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));

var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var token = new JwtSecurityToken(_config["Jwt:Issuer"],
          _config["Jwt:Issuer"],
          claims,
          expires: DateTime.Now.AddMinutes(30),
          signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);

在startup.cs中

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = Configuration["Jwt:Issuer"],
            ValidAudience = Configuration["Jwt:Issuer"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
        };
    });

有人,请解释一下这段代码的问题是什么?

HTTP 请求

已解决:发生这种情况没有到达代码 app.UseAuthentication()

【问题讨论】:

    标签: c# authentication asp.net-core user-roles


    【解决方案1】:

    您的代码看起来不错。当您在 HTTP 请求的标头中发送令牌时。您是否附加了授权类型?

    您需要在 HTTP 请求的标头中添加授权类型 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization

    在此处检查身份验证方案 http://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml

    您需要的是承载认证方案。您可以阅读此链接以获取有关详细信息的更多信息 https://www.rfc-editor.org/rfc/rfc6750#section-2.1

    所以,您的授权标头看起来像

    httpClient.DefaultHeaders.Add("Authorization", "Bearer " + your token);
    

    你可以通过像这样使用它来让它与你当前的设置一起工作

    [Authorize("Bearer", (Roles = "Manager")]
    

    【讨论】:

    • 感谢您的回答。是的,我正在发送带有 http 请求的授权类型。 (刚刚添加了一张图片来提问)。 [Authorize("Bearer", (Roles = "Manager")] dosen't work 给了我一个例外。
    • 什么异常,它给出了吗?您是否尝试过不使用角色管理器部分? [授权(“承载”)]
    【解决方案2】:

    对不起,我太笨了。
    这个问题的原因是没有使用app.UseAuthentication();

    就我而言,我不小心将它添加到生产环境范围内。有点像……

    else if (env.IsProduction())
       {
           ....
           app.UseAuthentication();
       }
    

    我的程序在开发环境中运行。所以app.UseAuthentication(); 没有到达。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-13
      • 2019-12-30
      • 2014-04-09
      • 2018-02-14
      • 2013-12-30
      • 1970-01-01
      • 2020-08-12
      • 1970-01-01
      相关资源
      最近更新 更多