Ali
Ali

Reputation: 1152

ASP.Net MVC individual (identity) authorization based on role id not working

I am using individual authentication in ASP.Net MVC 5.

I seed the "Admin" user in the context along with a password "12345678" and it's role "Owner". As in here:

if (!context.Roles.Any(r => r.Name == "Owner"))
{
    var rolestore = new RoleStore<IdentityRole>(context);
    var rolemanager = new RoleManager<IdentityRole>(rolestore);
    var role = new IdentityRole {Name = "Owner"};

    rolemanager.Create(role);
    if (!context.Users.Any(u => u.UserName == "Admin"))
    {
        var userstore = new UserStore<AppUser>(context);
        var usermanager = new UserManager<AppUser>(userstore);
        var user = new AppUser()
        {
            UserName = "Admin",
            PasswordHash = usermanager.PasswordHasher.HashPassword("12345678"),
            Role = "Owner"
        };

            usermanager.Create(user);
            usermanager.AddToRole(user.Id, "Owner");
        }
    }
}

Problem:
I need to use role-based authentication in my app but when I use [Authorize(Roles = "Owner")] I'm redirected to the login page.

But using either [Authorize] or [Authorize (Users = "Admin")] work fine, but I need the role-based authentication to work.

Troubleshooting that I've done so far:
1- Enabling the lazy-loading in the context this.Configuration.LazyLoadingEnabled = true;
2- Removing the <remove name="RoleManager"/>from Web.config
3- Making sure the database to see if the Admin is related to the Owner role
enter image description here
4- Logging out and logging in again to reset the cookie

Yet it's interesting that [Authorize(Roles = "Owner")] isn't working. Please help me. Thank you

Upvotes: 0

Views: 982

Answers (1)

Swagata Prateek
Swagata Prateek

Reputation: 1086

Could you kindly make sure the cookie that contains the auth certificate comes with a claim that contains the role in the certificate?

Authorize would only read your auth certificate and try to figure out whether there are any roles mentioned or not. If your auth cookie doesn't contain any information on the roles of the authenticated user, it wont really work. :)

Upvotes: 1

Related Questions