簡體   English   中英

如何檢查azure活動目錄用戶是否已處於批准狀態

[英]How to check if an azure active directory user is already in an approle

我創建了一個Azure活動目錄用戶,並將用戶添加到了app角色。 現在我正在檢索此用戶並嘗試將其添加到更多應用程序角色。

var activeDirectoryUser = client.Users.Where(u => u.UserPrincipalName == user.UserName).ExecuteSingleAsync().Result as User;

作為預防措施,我想在添加之前首先檢查用戶是否已經處於app角色,但問題是User對象上的ApproleAssignments字段始終為空。 即使您用戶具有應用程序角色分配,如果我嘗試將用戶添加到相同的應用程序角色,我也會收到錯誤。

創建新的應用角色分配。

var appRoleAssignment = new AppRoleAssignment
{
    Id = appRole.Id,
    ResourceId = Guid.Parse(servicePrincpal.ObjectId),
    PrincipalType = "User",
    PrincipalId = Guid.Parse(user.ObjectId)
};

if(IsUserInAppRole(user,appRoleAssignment))return;

user.AppRoleAssignments.Add(appRoleAssignment);
user.UpdateAsync().Wait();

檢查用戶是否處於app角色。

private bool IsUserInAppRole(User user, AppRoleAssignment appRoleAssignment)
{
    var userInApprole = user.AppRoleAssignments.Where(ara => ara.ObjectId == appRoleAssignment.Id.ToString());
    return userInApprole.Any();
}

我正在使用最新版本的Microsoft.Azure.ActiveDirectory.GraphClient

回復晚了非常抱歉。 以下代碼對我有用。 不確定是否需要使用IUserFetcher接口,但LINQ查詢失敗,因為您正在將賦值的objectID與appRole Id進行比較。 您需要比較的是作業的ID。

var userFetcher = user as IUserFetcher;
IPagedCollection<IAppRoleAssignment> rawObjects = userFetcher.AppRoleAssignments.ExecuteAsync().Result;

IList<IAppRoleAssignment> assignments = rawObjects.CurrentPage.ToList();
IAppRoleAssignment a = null;
a = assignments.Where(ara => ara.Id.Equals(appRole.Id)).First();
if (a != null) {
    Console.WriteLine("Found assignment {0} for user {1}", appRole.Id, user.DisplayName);
}

希望這可以幫助...

var userFetcher = user as IUserFetcher; 
IPagedCollection rawObjects = userFetcher.AppRoleAssignments.ExecuteAsync().Result;
IList<IAppRoleAssignment> assignments = rawObjects.CurrentPage.ToList();

上面的代碼行導致異常,因為未執行轉換,如果將其轉換為:

IPagedCollection rawObjects = 
         (IPagedCollection)userFetcher.AppRoleAssignments.ExecuteAsync().Result;

IList<IAppRoleAssignment> assignments = 
         (IList<IAppRoleAssignment>)rawObjects.CurrentPage.ToList();

代碼編譯成功,但運行時異常如下:

無法將類型'System.Collections.Generic.List'隱式轉換為'System.Collections.Generic.IList'。 存在顯式轉換(您是否錯過了演員?)

你能指導一下如何使用這兩個陳述嗎?

更新:

private static bool IsUserInRole(User user, AppRole appRole, bool roleAlreadyAssigned = false)
        {
        var userFetcher = user as IUserFetcher;
        IPagedCollection rawObjects = (IPagedCollection)userFetcher.AppRoleAssignments.ExecuteAsync().Result;

        foreach (IAppRoleAssignment item in rawObjects.CurrentPage)
            {
            if (item.Id == appRole.Id)
                {
                roleAlreadyAssigned = true; break;
                }

            }
        return roleAlreadyAssigned;
        }

上面的代碼對我有用。 試試這個,希望這會有所幫助:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM