Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

aspnetcore.identity - in role, but getting denied access

Core 2.0, using AspnetCore.Identity. I created a few roles, including "Admin".

    //initializing custom roles 
    var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
    var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
    string[] roleNames = { "Admin", "Training", "Operations", "Membership", "Individual" };
    IdentityResult roleResult;

    foreach (var roleName in roleNames)
    {
        var roleExist = await RoleManager.RoleExistsAsync(roleName);
        // ensure that the role does not exist
        if (!roleExist)
        {
            //create the roles and seed them to the database: 
            roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName)); 
        }
    }

I checked the SQL tables, and they're all there.:

enter image description here

Then I add myself to the Admin role (not the full method, but the relevant parts):

    var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
    var _eric = await UserManager.FindByEmailAsync("[email protected]");
        await UserManager.AddToRoleAsync(_eric, "Admin");

I check the tables, and I'm in there (along with another guy I added to a different role):

enter image description here

I then travel over to my method and slap Authorize on it with two of the roles, one of which I'm in (Admin):

[Authorize(Roles ="Training, Admin")]
public ActionResult Index()
{



    return View();
}

And then I get access denied. I'm missing something, but can't figure out what step I messed up. User is in there, I'm logged in, the data tables show me as having the role assigned, and the Authorize tag looks good.

like image 463
Eric Avatar asked Mar 13 '18 15:03

Eric


People also ask

What is Aspnetcore identity?

ASP.NET Core Identity: Is an API that supports user interface (UI) login functionality. Manages users, passwords, profile data, roles, claims, tokens, email confirmation, and more.

How do you get user role from net core identity?

Show activity on this post. var user = await _userManager. FindByIdAsync(UserId); var roles = await _userManager. GetRolesAsync(user); return OK(new { User = user, Roles = roles });

What is identity How can we configure it in asp net core application?

ASP.NET Core Identity uses default values for settings such as password policy, lockout, and cookie configuration. These settings can be overridden in the Startup class.


1 Answers

Roles are claims and claims are loaded only on sign in. If you modify a claim (such as by adding a role), you must sign the user out and either automatically sign them back in or prompt the user to re-authenticate, to reload the claims.

like image 59
Chris Pratt Avatar answered Nov 15 '22 11:11

Chris Pratt