Advertisement
Guest User

Untitled

a guest
Aug 30th, 2016
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. public static async Task<IServicePrincipal> GetServicePrincipalAsync(string accessToken, string tenantId, string clientId)
  2. {
  3. var graphClient = NewActiveDirectoryClient(accessToken, tenantId);
  4. var matches = await graphClient.ServicePrincipals.Where(sp => sp.AppId == clientId).ExecuteAsync();
  5. return matches.CurrentPage.ToList().FirstOrDefault();
  6. }
  7. private static ActiveDirectoryClient NewActiveDirectoryClient(string accessToken, string tenantId)
  8. {
  9. TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
  10. tcs.SetResult(accessToken);
  11. return new ActiveDirectoryClient(
  12. new Uri($"{GraphApiBaseUrl}{tenantId}"),
  13. async () => { return await tcs.Task; });
  14. }
  15.  
  16. public static async Task AssignRoleToPrincipalAsync(
  17. string accessToken,
  18. string subscriptionId,
  19. string scope,
  20. string roleName,
  21. string principalObjectId)
  22. {
  23. using (var client = NewAuthorizationManagementClient(accessToken, subscriptionId))
  24. {
  25. RoleDefinition roleDef = (await FindRoleDefinitionAsync(accessToken, subscriptionId, scope, roleName)).FirstOrDefault();
  26. if (roleDef == null)
  27. throw new Exception($"Role was not found: {roleName}");
  28. var props = new RoleAssignmentProperties()
  29. {
  30. PrincipalId = principalObjectId,
  31. RoleDefinitionId = roleDef.Id
  32. };
  33. await client.RoleAssignments.CreateAsync(scope, Guid.NewGuid().ToString("N"), props);
  34. }
  35. }
  36.  
  37. private static AuthorizationManagementClient NewAuthorizationManagementClient(string accessToken, string subscriptionId)
  38. {
  39. return new AuthorizationManagementClient(new TokenCredentials(accessToken)) { SubscriptionId = subscriptionId};
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement