Search code examples
asp.netasp.net-corewindows-authenticationasp.net-core-webapi

Retrieve all the roles (groups) a user is a member of in ASP.Net Core API


I'm trying to retrieve all roles the user is in.

This one works ok on my local IIS as I'm the one who is logged in, but when I put API to the server it retrieves not mine roles.

    [Authorize(Roles = "Admin")]
    [HttpGet]
    public IActionResult Get()
    {
        WindowsIdentity user = WindowsIdentity.GetCurrent();

        var userRoles = from id in user.Groups
                         select id.Translate(typeof(NTAccount)).Value;

        return Ok(userRoles);
    }

If I change WindowsIdentity to IIdentity I'm getting correct User on local and server but I'm not able to access roles.

IIdentity user = User.Identity;
return Ok(user);

How can I retrieve list of all roles user accessing API is in?


Solution

  • It ended up that I was very close and it is simple if anyone need it. In the first example replace this one:

    WindowsIdentity user = WindowsIdentity.GetCurrent();
    

    with that one:

    var user = User.Identity as WindowsIdentity;