Get a list of groups that Azure AD user belongs to in claims

前端 未结 4 1757
野趣味
野趣味 2020-12-06 07:27

I am authenticating users of my web api against Azure Active Directory. Now I want to get a list of groups that this user belongs.

I changed application manifest to

4条回答
  •  再見小時候
    2020-12-06 07:43

    Here is what we did in a project:

    Sign in to https://portal.azure.com and click on Azure Active Directory -> App registrations -> -> Manifest and set groupMembershipClaims to 7. You can read more about this here:

    https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-application-manifest

    You can then access the user groups like this:

    [Route("api/[controller]")]
    [ApiController]
    public class CurrentUserController : ControllerBase
    {
        [HttpGet("groups")]
        [ProducesResponseType(typeof(IEnumerable), (int)HttpStatusCode.OK)]
        public IActionResult Groups()
        {
            return Ok(User.Claims.Where(claim => claim.Type == "groups").Select(c => new ClaimsViewModel() { Type = c.Type, Value = c.Value }));
        }
    }
    
    public class ClaimsViewModel
    {
        public string Type { get; set; }
        public string Value { get; set; }
    }
    

    Sample respons with fake Object IDs:

    [{"type":"groups","value":"12fef9e0-4b73-425d-91b7-30c027aa4945"},{"type":"groups","value":"12fef9e0-4b73-425d-91b7-30c027aa4946"},{"type":"groups","value":"12fef9e0-4b73-425d-91b7-30c027aa4947"},{"type":"groups","value":"12fef9e0-4b73-425d-91b7-30c027aa4948"},{"type":"groups","value":"12fef9e0-4b73-425d-91b7-30c027aa4949"}]
    

    Given these IDs you can then identify the groups in AD.

提交回复
热议问题