在Office 365中使用c#.net代码动态创建用户帐户

bij*_*vam 1 api account office365

我想在c#.net中使用示例应用程序,它可以使用Microsoft API在Office 365中创建用户.

我希望在代码中执行它,而不是使用Powershell.

Jef*_*hen 6

您可以使用Microsoft Graph API - 创建用户:

在Azure AD上注册Native Client应用程序,分配"Microsoft Graph">"读取和写入目录数据"权限.

在此输入图像描述

            string authority = "https://login.windows.net/yourdomain.onmicrosoft.com";

            string clientId = "{app_client_id}";

            Uri redirectUri = new Uri("http://localhost");

            string resourceUrl = "https://graph.microsoft.com";

            HttpClient client = new HttpClient();

            AuthenticationContext authenticationContext = new AuthenticationContext(authority, false);

            AuthenticationResult authenticationResult = authenticationContext.AcquireToken(resourceUrl,
                clientId, redirectUri, PromptBehavior.Always);

            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + authenticationResult.AccessToken);

            string content = @"{
                'accountEnabled': true,
                'displayName': 'testuser',
                'mailNickname': 'test',
                'passwordProfile': {
                    'forceChangePasswordNextSignIn': true,
                    'password': 'pass@wd12345'
                },
                'userPrincipalName': 'testuser@yourdomain.onmicrosoft.com'
            }";

            var httpContent = new StringContent(content, Encoding.GetEncoding("utf-8"), "application/json");

            var response = client.PostAsync("https://graph.microsoft.com/v1.0/users", httpContent).Result;

            Console.WriteLine(response.Content.ReadAsStringAsync().Result);
Run Code Online (Sandbox Code Playgroud)