Stried
Stried

Reputation: 1

ASP.NET Core 6 authorization ClaimTypes.Role not authorizing the right roles

I'm quite new to this and still learning and have looked up the Microsoft documentations, but to no avail. I'm currently trying to authorize the ClaimTypes.Role of Author, however, when tested with other roles, it seems to still bypass the authorization. Any advice helps!

I have added app.UseAuthentication() before app.useAuthorization().

This application was also created using Swagger and SwaggerUI, but I did not seem to be able to find people who have an issue with this while using Swagger.

Dependencies:

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
}

This is how the token is made, if relevant:

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

Edit:

This is the authentication scheme:

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

When logged in as GenericUser and a user role of User, I am still able to post data despite the authentication needing the user role of Author. In the token, the ClaimTypes.Role is also saved as User. The user data:

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

The author role:

email: "[email protected]"
id: 1
name: "GenericAuthor"
userRole: "Author"

Upvotes: 0

Views: 605

Answers (0)

Related Questions