Search code examples
c#asp.netasp.net-mvcasp.net-identityasp.net-identity-2

How to obtain roles from ASP.NET Identity ApplicationGroupRoles table


I can retrieve all the roles for a user from AspNetUserRoles table in the prior version of ASP.NET Identity as shown below:

ApplicationUser user = UserManager.FindByName(model.UserName);
string userId = user != null ? user.Id : null;
var roles = userId != null ? UserManager.GetRoles(userId) : null;
if (roles != null)
{
    foreach (var item in roles)
    {
        //Assign user roles
        UserManager.AddToRole(userId, item);
    }
}

However, as the roles are assigned to the users via ApplicationGroupRoles and ApplicationUserGroups tables, this UserManager.GetRoles(userId) method does not works as it only retrieves roles from AspNetUserRoles table. So, how to manage to retrieve roles for a given user i.e. looking at ApplicationUserGroups first then ApplicationGroupRoles table? Or is the only way to retrieve them by using sql command? Any help would be appreciated.


Solution

  • Finally I use the following statements in order to obtain related values:

    ApplicationGroupManager gm = new ApplicationGroupManager();
    string roleName = RoleManager.FindById("").Name; //Returns Role Name by using Role Id 
    var userGroupRoles = gm.GetUserGroupRoles(""); //Returns Group Id and Role Id by User Id var 
    groupRoles = gm.GetGroupRoles(""); //Returns Group Roles by using Group Id
    string[] groupRoleNames = groupRoles.Select(p => p.Name).ToArray(); //Assing Group Role Names to a string array
    


    //Returns Group Id and Role Id by using User Id parameter
    var userGroupRoles = groupManager.GetUserGroupRoles(""); 
    foreach (var role in userGroupRoles)
    {
        string roleName = RoleManager.FindById(role.ApplicationRoleId).Name;
        UserManager.AddToRole(user.Id, roleName);
    }
    


    //Sets the uıser's group id
    var defaultGroup = "";
    groupManager.SetUserGroups(newUser.Id, new string[] { defaultGroup });
    

    By using them, now I can easily retrieve the necessary values I need. Thanks a lot @rashfmnb.