· 7 years ago · Aug 27, 2018, 08:58 AM
1var listRoles = user.AppRoleAssignments.ToList();
2user.AppRoleAssignments.Remove(listRoles[0]); //just demo: you could remove the role as your wanted
3user.UpdateAsync().Wait();
4
5private static async Task<string> GetAppTokenAsync(string graphResourceId, string tenantId, string clientId, string secretKey)
6 {
7 string aadInstance = "https://login.microsoftonline.com/" + tenantId + "/oauth2/token";
8 AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance, false);
9 var result = await authenticationContext.AcquireTokenAsync(graphResourceId,
10 new ClientCredential(clientId, userId));
11 return result.AccessToken;
12 }
13
14var graphResourceId = "https://graph.windows.net";
15var tenantId = "tenantId";
16var clientId = "client Id";
17var secretKey = "secret key";
18var servicePointUri = new Uri(graphResourceId);
19var serviceRoot = new Uri(servicePointUri, tenantId);
20var activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async () => await GetAppTokenAsync(graphResourceId, tenantId, clientId, secretKey));
21
22Application appObject = new Application { DisplayName = "Test-Demo App" };
23 appObject.IdentifierUris.Add("https://localhost/demo/" + Guid.NewGuid());
24 appObject.ReplyUrls.Add("https://localhost/demo");
25 AppRole appRole = new AppRole
26 {
27 Id = Guid.NewGuid(),
28 IsEnabled = true,
29 DisplayName = "Something",
30 Description = "Anything",
31 Value = "policy.write"
32 };
33
34 appRole.AllowedMemberTypes.Add("User");
35 appObject.AppRoles.Add(appRole);
36 activeDirectoryClient.Applications.AddApplicationAsync(appObject).Wait();
37 // create a new Service principal
38 ServicePrincipal newServicePrincpal = new ServicePrincipal
39 {
40 DisplayName = appObject.DisplayName,
41 AccountEnabled = true,
42 AppId = appObject.AppId
43 };
44activeDirectoryClient.ServicePrincipals.AddServicePrincipalAsync(newServicePrincpal).Wait();
45
46User user = (User) activeDirectoryClient.Users.GetByObjectId("userobjectId").ExecuteAsync().Result;
47AppRoleAssignment appRoleAssignment = new AppRoleAssignment
48{
49 Id = appRole.Id,
50 ResourceId = Guid.Parse(newServicePrincpal.ObjectId),
51 PrincipalType = "User",
52 PrincipalId = Guid.Parse(user.ObjectId),
53
54 };
55user.AppRoleAssignments.Add(appRoleAssignment);
56user.UpdateAsync().Wait();
57
58var listRoles = user.AppRoleAssignments.ToList();
59user.AppRoleAssignments.Remove(listRoles[0]);
60user.UpdateAsync().Wait();