我试图找出如何使用Azure Active Directory的图谱API从组或用户中删除AppRoleAssignment
。我使用的是.NET SDK(Microsoft.Azure.ActiveDirectory.GraphClient)。
我已尝试使用每个DeleteAsync
上的标准IEntityBase
方法,但它失败并出现错误。它发出的HTTP请求如下所示:
DELETE /{tenantId}/directoryObjects/{appRoleAssignment ObjectID}/Microsoft.DirectoryServices.AppRoleAssignment?api-version=1.5
因400错误请求而失败并显示错误"不支持对此资源类型的直接查询。"
这不是根据this Microsoft blog post使用Graph API删除AppRoleAssignments的正确方法,它表示您需要执行如下所示的HTTP请求:
DELETE /{tenantId}/users/{user object ID}/appRoleAssignments/{appRoleAs}?api-version=1.5
如果我使用HttpClient使用该URL格式进行手动HTTP请求,它可以工作,但我想知道如何在.NET库的范围内执行此操作,而不是自己执行手动HTTP请求。
如何通过.NET库删除AppRoleAssignments?
答案 0 :(得分:3)
虽然未修复,但您可以发出手动HTTP请求,但仍使用Azure AD SDK来获取令牌。像这样:
var tenantId = "<guid> tenant id";
var appId = "<guid> your Azure app id";
var appKey = "your app key";
var authority = "i.e. https://login.windows.net/mycompany.onmicrosoft.com";
var graphUrl = "https://graph.windows.net/";
public async Task RemoveRoleFromUser(Guid userId, string roleObjectId) {
var uri = string.Format("{0}/users/{1}/appRoleAssignments/{2}?api-version=1.5", tenantId, userId, roleObjectId);
await ExecuteRequest<object>(uri, HttpMethod.Delete);
}
private async Task<T> ExecuteRequest<T>(string uri, HttpMethod method = null, Object body = null) where T : class {
if (method == null) method = HttpMethod.Get;
T response;
var token = await AcquireTokenAsyncForApplication();
using (var httpClient = new HttpClient { BaseAddress = getServicePointUri() }) {
var request = new HttpRequestMessage(method, uri);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
if (body != null) {
request.Content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json");
}
var responseMessage = await httpClient.SendAsync(request).ConfigureAwait(false);
responseMessage.EnsureSuccessStatusCode();
response = await responseMessage.Content.ReadAsAsync<T>();
}
return response;
}
private async Task<string> AcquireTokenAsyncForApplication() {
ClientCredential clientCred = new ClientCredential(appId, appKey);
var authenticationContext = new AuthenticationContext(authority, false);
AuthenticationResult authenticationResult = authenticationContext.AcquireToken(graphUrl, clientCred);
return authenticationResult.AccessToken;
}
private Uri getServicePointUri() {
Uri servicePointUri = new Uri(graphUrl);
Uri serviceRoot = new Uri(servicePointUri, tenantId);
return serviceRoot;
}
答案 1 :(得分:0)
ActiveDirectoryClient client = AuthenticationHelper.GetActiveDirectoryClient();
user = (User) await client.Users.GetByObjectId(objectId).ExecuteAsync();
var roleId = "";
await user.AppRoleAssignments.Where(t=>t.ObjectId==roleId).FirstOrDefault().DeleteAsync();
以下网站可能会有所帮助:
https://github.com/AzureADSamples/WebApp-RoleClaims-DotNet
https://github.com/AzureADSamples/WebApp-GraphAPI-DotNet