Search code examples
azure-active-directoryjwtasp.net-core-webapiazure-ad-graph-api

WEB API Authorization through group membership with JWT authentication


The WEB API application is authenticated using JWT token passed by the client app. Given the token from the client app I want to perform additional check to see if the user from the token belongs to a security group using GRAPH API and authorize access to the API based on that.


Solution

  • Please note that, if you want to authorize user through group membership you have to make use of Authorization Code Flow to acquire the token.

    Make sure to change the settings in the Portal like below:

    Go to App Registration -> Your App -> Token Configuration -> Add Group Claim

    enter image description here

    Go to Manifest and update "groupMembershipClaims": "SecurityGroup" like below:

    enter image description here

    I tried to reproduce the same via Postman and generated token via Authorization Code Flow like below:

    GET https://login.microsoftonline.com/TenantID/oauth2/v2.0/token
    grant_type:authorization_code
    
    client_id:client_id
    client_secret:client_secret
    scope:scope
    code:code
    redirect_uri: redirect_uri
    

    enter image description here

    When I decoded the token, Group IDs are included like below:

    enter image description here

    You can check the below code sample to check if value of Group Name exists in Sessions or in User claims:

      public static bool CheckUsersGroupMembership(AuthorizationHandlerContext context, string GroupName, IHttpContextAccessor _httpContextAccessor)
      {
          bool result = false;
          if (HasOverageOccurred(context.User))
          {
              var groups = GetUserGroupsFromSession(_httpContextAccessor.HttpContext.Session);
              if (groups?.Count > 0 && groups.Contains(GroupName))
              {
                  result = true;
              }
          }
          else if (context.User.Claims.Any(x => x.Type == "groups" && x.Value == GroupName))
          {
              result = true;
          }
          return result;
      }
    

    To know more in detail, please refer below GitHub Blog for sample code:

    Azure active-directory-groupclaims: .NET web app that uses Azure AD groups for authorization