public static string GetGroupObjectIdFromName(DirectoryDataService directoryService, string name)
        {
            QueryOperationResponse <Group> response;
            //WebRetryHelper is a retries function with exponential back off in the case of transient exception
            DataServiceQuery <Group> groups = new WebRetryHelper <DataServiceQuery <Group> >(() => directoryService.groups).Value;

            groups   = (DataServiceQuery <Group>)(groups.Where(group => String.Compare(group.displayName, name) == 0));
            response = groups.Execute() as QueryOperationResponse <Group>;
            List <Group> groupList = response.ToList();

            if (groupList.Count == 0)
            {
                return(null);
            }
            return(groupList[0].objectId);
        }
        public ActionResult RoleMappingSubmit(FormCollection formCollection)
        {
            //remove role mapping assignments marked by checkboxes
            XmlHelper.RemoveRoleMappingsFromXml(formCollection);

            //add new role mapping assignment
            if (formCollection != null && formCollection["name"].Length > 0)
            {
                User   user     = new WebRetryHelper <User>(() => DirectoryService.users.Where(it => (it.userPrincipalName.Equals(formCollection["name"]))).SingleOrDefault()).Value;
                string objectId = (user == null) ? null : user.objectId;
                if (objectId == null)
                {
                    objectId = GetGroupObjectIdFromName(DirectoryService, formCollection["name"]);
                }
                if (objectId == null)
                {
                    return(RedirectToAction("Error", "Home", new { errorMessage = "User/Group not found." }));
                }
                XmlHelper.AppendRoleMappingToXml(formCollection, objectId);
            }
            return(RedirectToAction("RoleMappings", "Role"));
        }
        public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
        {
            if (incomingPrincipal != null && incomingPrincipal.Identity.IsAuthenticated == true)
            {
                //get the tenantId
                string tenantId = incomingPrincipal.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

                // Use the DirectoryDataServiceAuthorizationHelper graph helper API
                // to get a token to access the Windows Azure AD Graph
                string      clientId = ConfigurationManager.AppSettings["ClientId"];
                string      password = ConfigurationManager.AppSettings["Password"];
                AADJWTToken token    = DirectoryDataServiceAuthorizationHelper.GetAuthorizationToken(tenantId, clientId, password);

                // initialize a graphService instance. Use the JWT token acquired in the previous step.
                DirectoryDataService graphService = new DirectoryDataService(tenantId, token);

                // get the user's ObjectId
                String currentUserObjectId = incomingPrincipal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

                // Get the User object by querying Windows Azure AD Graph
                User currentUser = new WebRetryHelper <User>(() => graphService.directoryObjects.OfType <User>().Where(it => (it.objectId == currentUserObjectId)).SingleOrDefault()).Value;

                /*
                 * TaskTracker defines four roles that are specific to this app:
                 * "Admin", "Observer", "Writer", "Approver". These app roles are
                 * different from the roles that are built into Windows Azure AD,
                 * e.g. "Company Administrator", "User Account Administrator".
                 *
                 * This code uses the memberOf property of the User object to get
                 * the user's built-in roles. If the user has the "Company Administrator"
                 * built-in role, the app assigns the user to the "Admin" app role.
                 */

                // get the user's built-in roles
                new WebRetryHelper <object>(() => graphService.LoadProperty(currentUser, "memberOf"));
                List <Role> currentRoles = currentUser.memberOf.OfType <Role>().ToList();

                //if the user is a Company Administrator (Global Administrator),
                // assign them the "Admin" role in the app.
                foreach (Role role in currentRoles)
                {
                    if (role.displayName.Equals("Company Administrator"))
                    {
                        ((ClaimsIdentity)incomingPrincipal.Identity).AddClaim(new Claim(ClaimTypes.Role, "Admin", ClaimValueTypes.String, "TaskTrackerSampleApplication"));
                    }
                }

                /*
                 * To determine the user's group membership, TaskTracker uses
                 * the getCompleteGroupMembership function, which calls the getMemberGroups
                 * function, which returns the transitive group membership of the user.
                 */

                // Now, query transitive group membership of the user
                List <string> completeGroupMembership = new WebRetryHelper <List <String> >(() => graphService.GetCompleteGroupMembership(tenantId, currentUserObjectId, token)).Value;

                //Store the user's groups as claims of type "Group"
                foreach (string groupId in completeGroupMembership)
                {
                    Debug.WriteLine("adding " + groupId);
                    ((ClaimsIdentity)incomingPrincipal.Identity).AddClaim(new Claim("Group", groupId, ClaimValueTypes.String, "WindowsAzureADGraph"));
                }

                //Get role assignments
                foreach (string role in getRoles(currentUserObjectId, completeGroupMembership))
                {
                    //Store the user's application roles as claims of type Role
                    ((ClaimsIdentity)incomingPrincipal.Identity).AddClaim(new Claim(ClaimTypes.Role, role, ClaimValueTypes.String, "TaskTrackerSampleApplication"));
                }
            }
            return(incomingPrincipal);
        }