Example #1
0
        /// <summary>
        /// At the time of creating this application, there was no support for adding app-only permissions using the .NET AAD Graph Client SDK
        /// </summary>
        /// <param name="client"></param>
        /// <param name="grant"></param>
        /// <returns></returns>
        private static async Task AddApplicationPermissionsGrantAsync(IActiveDirectoryClient client, OAuthGrant grant)
        {
            var token = await AuthenticationHelper.AcquireAADTokenAsyncForUser();

            var webClient = new HttpClient();

            webClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            foreach (var graphPermissionId in grant.ApplicationPermissions)
            {
                var    uri      = $"{GlobalConstants.AADGraphResourceUrl}/{GlobalConstants.GraphTenantName}/servicePrincipals/{grant.ApplicationServicePrincipal.ObjectId}/appRoleAssignments?api-version=1.6";
                string jsonBody = JsonConvert.SerializeObject(new
                {
                    id            = graphPermissionId,
                    principalId   = grant.ApplicationServicePrincipal.ObjectId,
                    principalType = "ServicePrincipal",
                    resourceId    = grant.ResourceServicePrincipal.ObjectId
                });

                var response = await webClient.PostAsync(uri, new StringContent(jsonBody, Encoding.UTF8, "application/json"));

                if (!response.IsSuccessStatusCode)
                {
                    Program.WriteError($"\nError adding App-only Permissions for {grant.Application.DisplayName}: {response.StatusCode}");
                }
            }
        }
Example #2
0
        public static async Task <User> CreateNewUser(IActiveDirectoryClient client, VerifiedDomain defaultDomain,
                                                      string firstName, string lastName, int phoneNumber, string principalName)
        {
            // **********************************************************
            // Requires Directory.ReadWrite.All or Directory.AccessAsUser.All, and the signed in user
            // must be a privileged user (like a company or user admin)
            // **********************************************************

            User newUser = new User();

            if (defaultDomain.Name != null)
            {
                newUser.DisplayName = firstName + " " + lastName;
                //newUser.UserPrincipalName = firstName.ToLower() + "." + lastName.ToLower() + "@" +
                //                            defaultDomain.Name;
                newUser.UserPrincipalName = principalName;
                newUser.AccountEnabled    = true;
                newUser.TelephoneNumber   = phoneNumber.ToString();
                newUser.MailNickname      = firstName + lastName;
                newUser.PasswordProfile   = new PasswordProfile
                {
                    Password = "******",
                    ForceChangePasswordNextLogin = true
                };
                newUser.UsageLocation = "PL";

                await client.Users.AddUserAsync(newUser);

                _dialogService.Show(DialogType.Success, $"New User {newUser.DisplayName} was created");
            }
            return(newUser);
        }
Example #3
0
        /// <summary>
        /// Based on the YOUR AAD ApplicationId determine if the Tenant already has the ServicePrincipal in their directory
        /// </summary>
        /// <param name="client"></param>
        /// <param name="applicationId"></param>
        /// <returns></returns>
        private static async Task <IServicePrincipal> GetServicePrincipalAsync(IActiveDirectoryClient client, string applicationId)
        {
            IPagedCollection <IServicePrincipal> servicePrincipals = null;

            try
            {
                servicePrincipals = await client.ServicePrincipals.ExecuteAsync();
            }
            catch (Exception e)
            {
                Program.WriteError("\nError getting Service Principal {0}", Program.ExtractErrorMessage(e));
            }

            while (servicePrincipals != null)
            {
                List <IServicePrincipal> servicePrincipalsList = servicePrincipals.CurrentPage.ToList();
                IServicePrincipal        servicePrincipal      =
                    servicePrincipalsList.FirstOrDefault(x => x.AppId.Equals(applicationId));

                if (servicePrincipal != null)
                {
                    return(servicePrincipal);
                }

                servicePrincipals = await servicePrincipals.GetNextPageAsync();
            }

            return(null);
        }
Example #4
0
        private static async Task <ITenantDetail> GetTenantDetails(IActiveDirectoryClient client, string tenantId)
        {
            //*********************************************************************
            // The following section may be run by any user, as long as the app
            // has been granted the minimum of User.Read (and User.ReadWrite to update photo)
            // and User.ReadBasic.All scope permissions. Directory.ReadWrite.All
            // or Directory.AccessAsUser.All will also work, but are much more privileged.
            //*********************************************************************


            //*********************************************************************
            // Get Tenant Details
            // Note: update the string TenantId with your TenantId.
            // This can be retrieved from the login Federation Metadata end point:
            // https://login.windows.net/GraphDir1.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml
            //  Replace "GraphDir1.onMicrosoft.com" with any domain owned by your organization
            // The returned value from the first xml node "EntityDescriptor", will have a STS URL
            // containing your TenantId e.g. "https://sts.windows.net/4fd2b2f2-ea27-4fe5-a8f3-7b1a7c975f34/" is returned for GraphDir1.onMicrosoft.com
            //*********************************************************************

            ITenantDetail tenant = null;

            IPagedCollection <ITenantDetail> tenantsCollection = await client.TenantDetails
                                                                 .Where(tenantDetail => tenantDetail.ObjectId.Equals(tenantId)).ExecuteAsync();

            List <ITenantDetail> tenantsList = tenantsCollection.CurrentPage.ToList();

            if (tenantsList.Count > 0)
            {
                tenant = tenantsList.First();
            }

            if (tenant == null)
            {
                _dialogService.Show(DialogType.Error, "Tenant not found");
                return(null);
            }
            else
            {
                TenantDetail  tenantDetail = (TenantDetail)tenant;
                StringBuilder sb           = new StringBuilder();
                sb.AppendLine("Tenant Display Name: " + tenantDetail.DisplayName);

                // Get the Tenant's Verified Domains
                var initialDomain = tenantDetail.VerifiedDomains.First(x => x.Initial.HasValue && x.Initial.Value);
                sb.AppendLine("Initial Domain Name: " + initialDomain.Name);
                var defaultDomain = tenantDetail.VerifiedDomains.First(x => [email protected] && [email protected]);
                sb.AppendLine("Default Domain Name: " + defaultDomain.Name);

                // Get Tenant's Tech Contacts
                foreach (string techContact in tenantDetail.TechnicalNotificationMails)
                {
                    sb.AppendLine("Tenant Tech Contact: " + techContact);
                }
                sb.Remove(sb.Length - 2, 2);
                _dialogService.Show(DialogType.Success, sb.ToString());
                return(tenantDetail);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="GraphClient"/> class.
        /// </summary>
        /// <param name="service">Provides access to core services.</param>
        /// <param name="client">Provides the ability to interact with the Microsoft AD Graph API.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="service"/> is null.
        /// or
        /// <paramref name="client"/> is null.
        /// </exception>
        public GraphClient(IExplorerService service, IActiveDirectoryClient client)
        {
            service.AssertNotNull(nameof(service));
            client.AssertNotNull(nameof(client));

            this.service = service;
            this.client  = client;
        }
        private static async Task CleanupPermissionGrantsAsync(IActiveDirectoryClient client, OAuthGrant grant)
        {
            IServicePrincipal servicePrincipal = await GetServicePrincipalAsync(client, grant.Application.AppId);

            if (servicePrincipal == null)
            {
                Log(string.Format("No existing service principal for app {0}", grant.Application.DisplayName));
                return;
            }
            Log(string.Format("Deleting existing service principal for app {0}", grant.Application.DisplayName));
            await servicePrincipal.DeleteAsync();
        }
Example #7
0
        /// <summary>
        /// To ensure the latest Service Principal with the most up-to-date permissions are created,
        /// if exists, remove the existing Service Principal for YOUR AAD application
        /// </summary>
        /// <param name="client"></param>
        /// <param name="grant"></param>
        /// <returns></returns>
        private static async Task CleanupPermissionGrantsAsync(IActiveDirectoryClient client,
                                                               OAuthGrant grant)
        {
            IServicePrincipal servicePrincipal = await GetServicePrincipalAsync(client, grant.Application.AppId);

            if (servicePrincipal == null)
            {
                Program.WriteInfo($"No existing service principal for app {grant.Application.DisplayName}");
                return;
            }
            Program.WriteInfo($"Deleting existing service principal for app {grant.Application.DisplayName}");
            await servicePrincipal.DeleteAsync();
        }
        public SolutionGroupManager([NotNull] IActiveDirectoryClient activeDirectoryClient,
                                    [NotNull] IActiveDirectoryPathProvider activeDirectoryPathProvider)
        {
            if (activeDirectoryClient == null)
            {
                throw new ArgumentNullException(nameof(activeDirectoryClient));
            }
            if (activeDirectoryPathProvider == null)
            {
                throw new ArgumentNullException(nameof(activeDirectoryPathProvider));
            }

            _activeDirectoryClient       = activeDirectoryClient;
            _activeDirectoryPathProvider = activeDirectoryPathProvider;
        }
Example #9
0
        public static async Task <Group> FindGroupByObjectId(IActiveDirectoryClient client, string groupId)
        {
            List <IGroup> foundGroups    = null;
            IGroup        retrievedGroup = null;

            IPagedCollection <IGroup> groupsCollection = await client.Groups
                                                         .Where(g => g.ObjectId.Equals(groupId))
                                                         .ExecuteAsync();

            foundGroups = groupsCollection.CurrentPage.ToList();

            if (foundGroups.Count > 0)
            {
                retrievedGroup = foundGroups[0];
            }
            return((Group)retrievedGroup);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="GraphClient"/> class.
        /// </summary>
        /// <param name="service">Provides access to core services.</param>
        /// <param name="customerId">Identifier for customer whose resources are being accessed.</param>
        /// <exception cref="ArgumentException">
        /// <paramref name="customerId"/> is empty or null.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="service"/> is null.
        /// </exception>
        public GraphClient(IExplorerService service, string customerId)
        {
            service.AssertNotNull(nameof(service));
            customerId.AssertNotEmpty(nameof(customerId));

            this.customerId = customerId;
            this.service    = service;

            this.client = new ActiveDirectoryClient(
                new Uri($"{this.service.Configuration.GraphEndpoint}/{customerId}"),
                async() =>
            {
                AuthenticationToken token = await this.service.TokenManagement.GetAppOnlyTokenAsync(
                    $"{this.service.Configuration.ActiveDirectoryEndpoint}/{customerId}",
                    this.service.Configuration.GraphEndpoint);

                return(token.Token);
            });
        }
Example #11
0
        /// <summary>
        /// If the ServicePrincipal does not already exist in the tenant's directory,
        /// then creates a ServicePrincipal for the specified application in the tenant's directory,
        /// otherwise return the found ServicePrincipal
        /// </summary>
        /// <param name="client"></param>
        /// <param name="application"></param>
        /// <returns>IServicePrincipal</returns>
        private static async Task <IServicePrincipal> CreateServicePrincipalAsync(IActiveDirectoryClient client, IApplication application)
        {
            IServicePrincipal servicePrincipal = null;

            if (application.AppId != null)
            {
                // does the Service Principal already exist?
                servicePrincipal = await GetServicePrincipalAsync(client, application.AppId);

                // if exists then return the found Service Principal
                if (servicePrincipal != null)
                {
                    return(servicePrincipal);
                }

                // if not found then create a Service Principal for this tenant
                servicePrincipal = new ServicePrincipal()
                {
                    AccountEnabled = true,
                    AppId          = application.AppId,
                    DisplayName    = application.DisplayName
                };

                try
                {
                    await client.ServicePrincipals.AddServicePrincipalAsync(servicePrincipal);
                }
                catch (Exception e)
                {
                    Program.WriteError("\nError creating Service Principal for {0}: {1}", application.DisplayName, Program.ExtractErrorMessage(e));
                    return(null);
                }
            }
            else
            {
                Program.WriteError("\nRefusing to create Service Principal for {0} because ApplicationID was not supplied", application.DisplayName);
                return(null);
            }


            return(servicePrincipal);
        }
Example #12
0
        public static async Task <bool> IsPrincipalNameAvailable(IActiveDirectoryClient client, string principalName)
        {
            //*********************************************************************
            // People picker
            // Search for a user using text string "Us" match against userPrincipalName, displayName, giveName, surname
            // Requires minimum of User.ReadBasic.All.
            //*********************************************************************

            List <IUser>             usersList     = null;
            IPagedCollection <IUser> searchResults = null;

            IUserCollection userCollection = client.Users;

            searchResults = await userCollection.Where(user =>
                                                       user.UserPrincipalName.StartsWith(principalName)).Take(1).ExecuteAsync();

            usersList = searchResults.CurrentPage.ToList();


            return(usersList.Count == 0);
        }
Example #13
0
        public UserGroupMembershipProvider([NotNull] IActiveDirectoryClient activeDirectoryClient,
                                           [NotNull] IActiveDirectoryPathProvider activeDirectoryPathProvider,
                                           [NotNull] IUserPrincipalProvider userPrincipalProvider)
        {
            if (activeDirectoryClient == null)
            {
                throw new ArgumentNullException(nameof(activeDirectoryClient));
            }
            if (activeDirectoryPathProvider == null)
            {
                throw new ArgumentNullException(nameof(activeDirectoryPathProvider));
            }
            if (userPrincipalProvider == null)
            {
                throw new ArgumentNullException(nameof(userPrincipalProvider));
            }

            _activeDirectoryClient       = activeDirectoryClient;
            _activeDirectoryPathProvider = activeDirectoryPathProvider;
            _userPrincipalProvider       = userPrincipalProvider;
        }
Example #14
0
 private static async Task AddDelegatedPermissionsGrantAsync(IActiveDirectoryClient client, OAuthGrant grant)
 {
     if (grant.DelegatedPermissions == "")
     {
         return;
     }
     try
     {
         // add the permissions
         await client.Oauth2PermissionGrants.AddOAuth2PermissionGrantAsync(new OAuth2PermissionGrant
         {
             ClientId    = grant.ApplicationServicePrincipal.ObjectId,
             ConsentType = "AllPrincipals", // all users
             ResourceId  = grant.ResourceServicePrincipal.ObjectId,
             Scope       = grant.DelegatedPermissions,
             ExpiryTime  = new DateTime().AddYears(100) // when the grant expires
         });
     }
     catch (Exception e)
     {
         Program.WriteError("\nError adding Delegated Permissions for {0}: {1}", grant.Application.DisplayName, Program.ExtractErrorMessage(e));
     }
 }
Example #15
0
 public UserStore(IActiveDirectoryClientAdapter activeDirectoryClientAdapter)
 {
     _activeDirectoryClient = activeDirectoryClientAdapter.GetActiveDirectoryClientAsApplication();
 }