Get User Roles with ASP.net Identity and Web API

tokyo0709

I am currently trying to get the given user's list of Roles and am having some trouble fitting this into the context we are using it in. I was able to get a list of all available roles with this API function earlier,

[HttpGet]
[Route("GetRoles")]
public async Task<ApiResponse<List<RoleViewModel>>> GetRoles()
{
    try
    {
        //Get Roles
        var roles = await (from r in _db.AspNetRoles
                     select new RoleViewModel { Id = r.Id, Name = r.Name}).ToListAsync();
        return new ApiResponse<List<RoleViewModel>>{ Success = true, Result =  roles };

    }
    catch(Exception ex)
    {
        return new ApiResponse<List<RoleViewModel>> { Success = false, Message = ex.Message };
    }

}

But can't seem to figure out what I need to throw into this one to get a list of the roles for the user. We went with Entity Frameworks Code First from Existing Database approach and are pulling from those tables. Strangely though there is no AspNetUserRoles table since I guess it is just relating the two tables AspNetUsers and AspNetRoles. Anyway, here is the function in question,

[HttpGet]
[Route("GetUserRoles")]
public async Task<ApiResponse<List<RoleViewModel>>> GetUserRoles(string userName)
{
    try
    {
        var userRoles = await (_db.AspNetUsers.FirstOrDefault(u => u.UserName == userName).AspNetRoles).ToListAsync();
    }
    catch (Exception ex)
    {
        return new ApiResponse<List<RoleViewModel>> { Success = false, Message = ex.Message };
    }
}

The current error I am getting is that AspNetRole does not contain a definition for ToListAsync(). I think the async stuff is throwing me a little. And lastly here is the RoleViewModel for reference,

public class RoleViewModel
{
    public string Id { get; set; }

    [Required]
    [StringLength(256)]
    public string Name { get; set; }
}

And the ApiResponse class,

public class ApiResponse<TResult>
{
    public bool Success { get; set; }
    public string Message { get; set; }
    public TResult Result { get; set; }
}

I feel like there should be a simple fix, but I just can't quite grasp what it is.

tokyo0709

Just found the answer to my problem. The main thing I was missing was utilization of the User Manager which made things so much easier. Then I just had to fit things into the functions I had already defined. Here is the code.

[HttpGet]
[Route("GetUserRoles")]
public async Task<ApiResponse<List<RoleViewModel>>> GetUserRoles(string userName)
{
    try
    {
        // Get the user in question
        var aspUser = (from u in _db.AspNetUsers
                       where u.UserName == userName
                       select u).FirstOrDefaultAsync();

        // Check if the user was found
        if (aspUser == null)
        {
            throw new Exception("User was not found");
        }

        // Get the roles associated with that user
        var userRoles = await UserManager.GetRolesAsync(aspUser.Result.Id.ToString());

        // Setup a RoleViewModel list of roles and iterate through userRoles adding them to the list
        List<RoleViewModel> roleList = new List<RoleViewModel>();
        foreach (var u in userRoles)
        {
            var item = new RoleViewModel { Name = u };
            roleList.Add(item);
        }

        return new ApiResponse<List<RoleViewModel>> { Success = true, Result = roleList };
    }
    catch (Exception ex)
    {
        return new ApiResponse<List<RoleViewModel>> { Success = false, Message = ex.Message };
    }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

ASP.NET Web API get user identity in controller constructor

How to get JWT authenticated sign-in user from identity claims in asp.net web api

ASP.net Identity OWIN cookie when user roles change?

How to check user is in many roles in asp.net identity

ASP.net Identity 2.1 Get all users with roles

ASP.NET Core Identity in a Web API

How do I seed user roles in Identity ASP.NET Core 2.1 (Identity Scaffolded)

Get a list of Roles as a List<string> as result in ASP.NET Core Web API

How to check if user is logged in to ASP.NET Core web application when using ASP.NET Core Web API to house identity

Access user identity from controller in ASP.NET Core Web API

ASP.Net Core: Get User Roles with LinQ Select method

Get user profile in ASP.net core API with Identity Server 4 Implicit Flow

ASP.NET Core Web API and roles authorization

ASP.NET Identity 2 hierarchical roles

unable to add roles in asp.net identity

Extra column on user-roles table when using custom identity user(ASP.NET 5.2EF 6 and Identity 2)

Remove User from Roles in ASP.NET Identity 2.x

Asp.NET Identity Roles not working when attempting to add Role to User

ASP.NET Core 2.0 Identity update user roles only after re-authorization

Asp.net core role based access identity / roles make user table self referencing

Identity Authorize Attribute Roles with Web API

Configuring Identity Server to use ASP.NET Identity roles

implementing roles in identity server 4 with asp.net identity

ASP.Net Core API: How to link User Identity to a Contact

User Authentication in ASP.NET Web API

Get all roles in asp.net core identity using a separate class

ASP.NET Core Identity - get current user

Get current user id in ASP.NET Identity 2.0

ASP.Net Identity with IdentityServer fails to get User in controller context