Home > Enterprise >  Why does GetRolesAsync() return no roles?
Why does GetRolesAsync() return no roles?

Time:11-29

I've added identity and authentication to an already existing API that was written in .net core 2.1.

There is for sure something funky going on as I am getting no roles returned when calling GetRolesAsync() like so:

var user = await _userManager.FindByEmailAsync(email);
var roles = await _userManager.GetRolesAsync(user);

I am able to create users ok using the following code:

                var newUser = new User
                {
                    UserName = model.Email,
                    Email = model.Email,
                    IsEnabled = true,
                    Name = model.FirstName   " "   model.LastName,
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    CreatedDate = DateTime.Now,
                    CreatedBy = user.Identity.Name
                };

                var result = await _userManager.CreateAsync(newUser, model.Password);

                if (result.Succeeded)
                {
                    foreach (var role in model.Roles)
                    {
                        result = await _userManager.AddToRoleAsync(newUser, role.ToString());
                    }

                    return newUser;
                }

This call adds the new user to AspnetUsers and also adds the user roles to AspNetUserRoles.

I am setting up authorisation in startup.cs like so:

            var key = Encoding.ASCII.GetBytes(Configuration.GetValue<string>("JwtSettings:Secret"));
            services
                .AddAuthorization()
                .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

            services.AddIdentity<User, ApplicationRole>()
                .AddEntityFrameworkStores<AccountContext>()
                .AddDefaultTokenProviders();


User class inherits IdentityUser:

    public partial class User : IdentityUser
    {
        // Some extra members
    }

ApplicationRole inherits IdentityRole:

    public partial class ApplicationRole : IdentityRole
    {
        // No members
    }

I am storing all entries in postgres database and values are being written and read ok.

The entries in AspNetUserRoles have been added manually but I added some using RoleManager then and same issue.

Why would I get no roles returned when I call GetRolesAsync() for a user that has been verified to exist?

I've tried a lot of the suggestions here but none have figured this out for me.

CodePudding user response:

Your code does not seem to have a problem, please add breakpoints to step through the debugging to see if one of the steps is not executed properly.

You did not get an error in the process of creating the user, which means that your creation process is correct, model.Roles also do exist in the RoleManager. When you call _userManager.FindByEmailAsync(email), check if user is the user you created and added the role to: enter image description here

Then,you can successfully get the user's role: enter image description here

Make sure you do store the user's role information correctly. Here is a complete example and here is the tutorial you can refer to. Please double check if there is something we missed that is causing this issue.

Hope this can help you.

CodePudding user response:

I've solved the problem:

I was creating new users using a User which inherited from IdentityUser like so:

public partial class User : IdentityUser
{
    public string Id { get; set; }
    ... and more
}

Inspecting the new user before AddToRoleAsync() showed me there was two Id members and one was marked as IdentityUser::Id. The wrong Id(User) was being assigned to the role.

I removed the Id member from ApplicationUser and all is good now.

  • Related