使用C#中的Azure AD Graph API向已创建的应用程序添加角色

时间:2018-11-23 07:35:02

标签: c# azure azure-active-directory azure-ad-graph-api

如何使用c#中的Azure AD Graph API在已经在azure广告上创建的应用程序中添加角色。
我在c#中创建了这样的角色:

 Guid _id = new Guid();

 AppRole appRole = new AppRole

    {
      AllowedMemberTypes = _AllowedMemberTypes,
      Description = "Admins can manage roles and perform all actions.",
      DisplayName = "Global Admin",
      Id = _id,
      IsEnabled = true,
      Value = "Admin"
    };  

使用哪种调用将使用Azure AD Graph API在应用程序中添加此新角色。

2 个答案:

答案 0 :(得分:2)

最后,我能够使用Azure Ad Graph API在azure上创建新角色

1)创建角色:

Guid _id = Guid.NewGuid();
List<String> _AllowedMemberTypes = new List<string> {
    "User"
};
AppRole appRole = new AppRole
{
    AllowedMemberTypes = _AllowedMemberTypes,
    Description = "Admins can manage roles and perform all actions.",
    DisplayName = "Global Admin",
    Id = _id,
    IsEnabled = true,
    Value = "Admin"

};

2)获取需要在其中创建角色的应用程序:

IPagedCollection<IApplication> pagedCollection = await activeDirectoryClient.Applications.Where(x => x.AppId == AppclientId).ExecuteAsync();
var appObject = pagedCollection.CurrentPage.ToList().FirstOrDefault();  

3)向Applicationa添加角色并更新应用程序:

 appObject.AppRoles.Add(appRole as AppRole);
 await appObject.UpdateAsync();

答案 1 :(得分:0)

您可以参考以下代码来分配应用程序角色。

1。获取访问令牌

private static async Task<string> GetAppTokenAsync(string graphResourceId, string tenantId, string clientId, string secretKey)
        {
            string aadInstance = "https://login.microsoftonline.com/" + tenantId + "/oauth2/token";
            AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance, false);
            var result = await authenticationContext.AcquireTokenAsync(graphResourceId,
                new ClientCredential(clientId, userId));
            return result.AccessToken;
        }

2。初始化graphclient。

var graphResourceId = "https://graph.windows.net";
var tenantId = "tenantId";
var clientId = "client Id";
var secretKey = "secret key";
var servicePointUri = new Uri(graphResourceId); 
var serviceRoot = new Uri(servicePointUri, tenantId);
var activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async () => await GetAppTokenAsync(graphResourceId, tenantId, clientId, secretKey));

3.create角色

AppRole appRole = new AppRole
{
    Id = Guid.NewGuid(),
    IsEnabled = true,
    Description = "Admins can manage roles and perform all actions.",
    DisplayName = "Global Admin",
    Value = "Admin"
};

4.add角色组合

User user = (User) activeDirectoryClient.Users.GetByObjectId("userobjectId").ExecuteAsync().Result;
AppRoleAssignment appRoleAssignment = new AppRoleAssignment
{
       Id = appRole.Id,
       ResourceId = Guid.Parse(newServicePrincpal.ObjectId),
       PrincipalType = "User",
       PrincipalId = Guid.Parse(user.ObjectId),

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