代码之家  ›  专栏  ›  技术社区  ›  Stried

ASP。NET Core 6授权ClaimTypes。角色未授权正确的角色

  •  0
  • Stried  · 技术社区  · 3 年前

    我对此很陌生,仍在学习,并查阅了微软的文档,但无济于事。我目前正在尝试授权 ClaimTypes.Role 属于 Author 然而,当与其他角色一起测试时,它似乎仍然绕过了授权。任何建议都有帮助!

    我添加了 app.UseAuthentication() 之前 app.useAuthorization() .

    这个应用程序也是使用Swagger和SwaggerUI创建的,但我似乎找不到在使用Swagger时对此有问题的人。

    依赖项:

    • 旋转皮带扣。AspNetCore v6.2.3
    • 微软AspNetCore。身份验证。JwtBearer 6.0.21版
    builder.Services.AddAuthorization(options =>
    {
        options.AddPolicy("AuthorOnly", policy => policy.RequireClaim(ClaimTypes.Role, "Author"));
    });
    
    [HttpPost, Authorize(Policy = "AuthorOnly")]
    public IActionResult AddTutorial(Tutorial tutorial)
    {
        var userID = GetUserID();
        var now = DateTime.Now;
    
        var myTutorial = new Tutorial()
                {
                    Title = tutorial.Title.Trim(),
                    Description = tutorial.Description.Trim(),
                    CreatedAt = now,
                    UpdatedAt = now,
                    UserID = userID,
                };
    
        context.Tutorials.Add(myTutorial);
        context.SaveChanges();
    
        return Ok(myTutorial); // returns a 200 status code
    }
    

    代币的制作方式如下(如果相关):

    private string CreateToken(User user)
    {
        string secret = configuration.GetValue<string>("Authentication:Secret");
        int tokenExpiresDays = configuration.GetValue<int>("Authentication:TokenExpiresDays");
    
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes(secret);
    
        // What kind of information is stored in the token 
        // Information that is most usually used for authentication/identification
        // https://learn.microsoft.com/en-us/dotnet/api/system.security.claims.claim?view=net-7.0 (For claims understanding)
        var tokenDescriptor = new SecurityTokenDescriptor
                {
                    // Subject is the entity (usually a user requesting access to a resource)
                    // ClaimsIdentity is a collection of claims that describe the properties and attributes of the subject
                    Subject = new ClaimsIdentity(new Claim[] 
                    {
                        new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                        new Claim(ClaimTypes.Name, user.Name),
                        new Claim(ClaimTypes.Email, user.Email),
                        new Claim(ClaimTypes.Role, user.UserRole)
                    }),
                    Expires = DateTime.UtcNow.AddDays(tokenExpiresDays),
                    // Specifies the signing key, signing key identifier, and security algorithms to generate a digital signature for SamlAssertion
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };
    
        var securityToken = tokenHandler.CreateToken(tokenDescriptor);
        string token = tokenHandler.WriteToken(securityToken);
    
        return token;
    }
    

    编辑

    这是身份验证方案:

    var secret = builder.Configuration.GetValue<string>("Authentication:Secret");
    builder.Services
        .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = false,
                ValidateAudience = false,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(
                    Encoding.UTF8.GetBytes(secret)
                ),
            };
        });
    

    以身份登录时 GenericUser 以及的用户角色 User ,尽管身份验证需要的用户角色,但我仍然能够发布数据 著者 。在令牌中,ClaimTypes。角色也另存为 使用者 . 用户数据:

    email: "[email protected]"
    id: 2
    name: "GenericUser"
    userRole: "User"
    

    作者角色:

    email: "[email protected]"
    id: 1
    name: "GenericAuthor"
    userRole: "Author"
    
    0 回复  |  直到 3 年前