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) { Log(string.Format("\nError adding Delegated Permissions for {0}: {1}", grant.Application.DisplayName, e.Message)); } }
private static async Task AddApplicationPermissionsGrantAsync(IActiveDirectoryClient client, OAuthGrant grant) { var token = await AuthenticationHelper.AcquireTokenAsyncForUser(); 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")); Log(response.ToString()); } }
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(); }