我有要求以編程方式在azure活動目錄中創建用戶或組。我搜索谷歌,我發現像使用圖形API,C#代碼等多種解決方案..但我有點困惑的方法。如何使用ASP.Net(C#)在Azure Active Directory中創建組/用戶?
任何人可以幫助我解決這些方法之間的差異,並建議我最好的方法?請讓我知道是否有任何代碼示例可用。
在此先感謝!
我有要求以編程方式在azure活動目錄中創建用戶或組。我搜索谷歌,我發現像使用圖形API,C#代碼等多種解決方案..但我有點困惑的方法。如何使用ASP.Net(C#)在Azure Active Directory中創建組/用戶?
任何人可以幫助我解決這些方法之間的差異,並建議我最好的方法?請讓我知道是否有任何代碼示例可用。
在此先感謝!
Azure廣告支持multiple protocols。要獲取Azure AD圖的標記,我們需要在OAuth 2.0/OpenId connect中選擇合適的流以與Azure AD進行交互。
例如,如果您正在開發Web應用程序,則OAuth代碼授權流程可能是一個不錯的選擇。如果該應用程序是守護程序應用程序或服務應用程序,則客戶端憑據流程是更好的一個。有關場景的更多信息,請參閱this document。
並且要在Web應用程序中獲取Azure AD Graph的令牌,可以參考this code sample。在此代碼示例的line of 104處,它獲取Azure AD Graph的訪問令牌。然後在控制器,可以使用下面的代碼來獲取從緩存中的令牌,並使用Azure的AD圖形用戶:
string graphResourceId = "https://graph.windows.net";
string tenantId = "xxx.onmicrosoft.com";
AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/xxx.onmicrosoft.com");
ClientCredential credential = new ClientCredential("{clientId}", "{secret}");
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationResult result = await authContext.AcquireTokenSilentAsync(graphResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
var accessToken = result.AccessToken;
Uri servicePointUri = new Uri(graphResourceId);
Uri serviceRoot = new Uri(servicePointUri, tenantId);
ActiveDirectoryClient graphClient = new ActiveDirectoryClient(serviceRoot, async() => await Task.FromResult(accessToken));
var user = new User();
user.AccountEnabled = true;
user.DisplayName = "testName";
user.UserPrincipalName = "[email protected]";
user.MailNickname = "testName";
user.UsageLocation = "US";
user.PasswordProfile = new PasswordProfile
{
Password = "xxxxxx",
ForceChangePasswordNextLogin = true
};
await graphClient.Users.AddUserAsync(user);
和應用程序需要Directory.ReadWrite.All
創建用戶和組。有關權限的更多詳細信息,請參閱here。
非常感謝菲爲解決方案。它真的幫了我很多。再次感謝 :-) –