azure - 如何使用 ASP.Net (C#) 在 Azure Active Directory 中创建组/用户?

标签 azure active-directory

我需要以编程方式在 Azure Active Directory 中创建用户或组。我在 google 上搜索,找到了多种解决方案,例如使用 Graph API、C# 代码等。但我对这种方法有点困惑。

任何人都可以帮助我了解这些方法之间的差异并建议我最好的方法吗?如果有任何可用的代码示例,请告诉我。

提前致谢!!

最佳答案

Azure 广告支持 multiple protocols 。要获取 Azure AD Graph 的 token ,我们需要在 OAuth 2.0/OpenId 连接中选择合适的流程来与 Azure AD 交互。

例如,如果您正在开发 Web 应用程序,OAuth 代码授予流程可能是一个不错的选择。如果应用程序是守护程序应用程序或服务应用程序,则客户端凭据流更好。更多场景可以引用this document

要在Web应用程序中获取Azure AD Graph的 token ,您可以引用this code sample 。在line of 104在此代码示例中,它获取 Azure AD Graph 的访问 token 。然后在 Controller 中,您可以使用以下代码从缓存中获取 token 并使用 Azure AD Graph 创建用户:

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 = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="53273620271d323e36132b2b2b7d3c3d3e3a30213c203c35277d303c3e" rel="noreferrer noopener nofollow">[email protected]</a>";
user.MailNickname = "testName";
user.UsageLocation = "US";
user.PasswordProfile = new PasswordProfile
{
    Password = "xxxxxx",
    ForceChangePasswordNextLogin = true
};

await graphClient.Users.AddUserAsync(user);

应用程序需要Directory.ReadWrite.All来创建用户和组。更详细的权限可以引用here .

关于azure - 如何使用 ASP.Net (C#) 在 Azure Active Directory 中创建组/用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43494220/

相关文章:

powershell 上的 Azure CLI 命令给出 '"c :\\\"Program' is not recognized as an internal or external command,

azure - 在 Azure DevOps 中删除源分支时如何删除 Azure Static Web App 分支预览环境?

windows - 在队列(例如 MSMQ)中发送电子邮件

git - $(System.PullRequest.SourceBranch) 未找到

azure - 如何在 Powershell 中向 Azure AAD 应用程序授予管理员同意?

c# - 从当前用户 appdata 文件夹中的文件读取 C#

linux - 尝试从 linux ldapsearch 命令获取 memberof 详细信息

testing - 如何使用 ADAM 运行单元测试?

php - 将 Windows Server 中的 Active Directory 与 Laravel 5 集成以实现多个用户角色

c# - 在 Windows Azure 中部署 WCF 应用程序