简体   繁体   English

C#控制台应用程序,用于使用Microsoft Graph在Azure Active Directory中创建用户

[英]C# Console App to Create User in Azure Active Directory using Microsoft Graph

How can I create an user in Azure AD using Microsoft Graph without having to login (from a console/service)? 如何使用Microsoft Graph在Azure AD中创建用户而无需登录(从控制台/服务)?

It seams all the examples out there are so that you have to login first using AD account. 它接缝了所有示例,因此您必须先使用AD帐户登录。

With this I get access denied. 有了这个我得到拒绝访问。

class Program {
    static void Main (string[] args) {

        Create ().Wait ();
        Console.ReadLine ();
    }

    private static async Task Create () {
        var graph = new GraphServiceClient (new AzureAuthenticationProvider ());
        try {
            var users = await graph.Users.Request ().GetAsync ();
            int requestNumber = 1;
            while (users.Count > 0) {
                Console.WriteLine ("Request number: {0}", requestNumber++);
                foreach (var u in users) {
                    Console.WriteLine ("User: {0} ({1})", u.DisplayName,
                        u.UserPrincipalName);
                }

                if (users.NextPageRequest != null) {
                    users = await users.NextPageRequest.GetAsync ();
                } else {
                    break;
                }
            }
        } catch (ServiceException x) {
            Console.WriteLine ("Exception occured: {0}", x.Error);
        }
    }

}

public class AzureAuthenticationProvider : IAuthenticationProvider {
    public async Task AuthenticateRequestAsync (HttpRequestMessage request) {

        string clientId = "IDHERE";
        string clientSecret = "SECRETHERE";

        string tenantName = "somedomain.com";
        string authString = "https://login.microsoftonline.com/" + tenantName;

        AuthenticationContext authContext = new AuthenticationContext (authString, false);

        ClientCredential creds = new ClientCredential (clientId, clientSecret);

        AuthenticationResult authResult = await authContext.AcquireTokenAsync ("https://graph.microsoft.com/", creds);

        request.Headers.Add ("Authorization", "Bearer " + authResult.AccessToken);
    }
}

OK, So here it is! OK,就在这里! I spent half day to figure out this and now it works. 我花了半天的时间弄清楚了,现在可以了。

Go to Azure Portal -> AD Section -> Register New App (Web App / API), Create new Key and save it. 转到Azure门户-> AD部分->注册新应用(Web应用/ API),创建新密钥并保存。

Required Permissions: 所需权限:

  • Application Permissions 申请权限
    • Read and write directory data 读写目录数据
  • Delegate Permissions (i think this doesn't matter) 委托权限(我认为这无关紧要)
    • Access the directory as the signed-in user 以登录用户身份访问目录
    • Read all users basic profile 阅读所有用户的基本资料
    • Sign in and read user profile 登录并阅读用户资料

Then from the Required Permissions blade click Grant Permissions at the top menu close to + Add button. 然后从“必需的权限”边栏选项卡中,单击靠近+添加按钮的顶部菜单中的“授予权限”。

Then the code is like this: 然后代码是这样的:

  class Program
{
    static void Main(string[] args)
    {

        Create().Wait();
        Console.ReadLine();
    }


    private static async Task Create()
    {
        var graph = new GraphServiceClient(new AzureAuthenticationProvider());
        try
        {
            var users = await graph.Users.Request().GetAsync();
            int requestNumber = 1;
            while (users.Count > 0)
            {
                Console.WriteLine("Request number: {0}", requestNumber++);
                foreach (var u in users)
                {
                    Console.WriteLine("User: {0} ({1})", u.DisplayName,
                        u.UserPrincipalName);
                }

                if (users.NextPageRequest != null)
                {
                    users = await users.NextPageRequest.GetAsync();
                }
                else
                {
                    break;
                }
            }
        }
        catch (ServiceException x)
        {
            Console.WriteLine("Exception occured: {0}", x.Error);
        }
    }

}

internal class AppModeConstants
{
    public const string ClientId = "YOUR_CLIENT_ID_HERE";
    public const string ClientSecret = "YOUR_SECRET_HERE";
    public const string TenantName = "YOUR_TENANT_NAME_HERE";  //somedomain.com
    public const string TenantId = "YOUR_TENANT_ID_HERE";
    public const string AuthString = GlobalConstants.AuthString + TenantName;
}


internal class GlobalConstants
{
    public const string AuthString = "https://login.microsoftonline.com/";
    public const string ResourceUrl = "https://graph.microsoft.com";
    public const string GraphServiceObjectId = "00000002-0000-0000-c000-000000000000";
}

public class AzureAuthenticationProvider : IAuthenticationProvider
{
    public async Task AuthenticateRequestAsync(HttpRequestMessage request)
    {         


        AuthenticationContext authContext = new AuthenticationContext(AppModeConstants.AuthString,false);

        ClientCredential creds = new ClientCredential(AppModeConstants.ClientId, AppModeConstants.ClientSecret);

        AuthenticationResult authResult = await authContext.AcquireTokenAsync(GlobalConstants.ResourceUrl,creds);

        request.Headers.Add("Authorization", "Bearer " + authResult.AccessToken);
    }
}  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法解决 C# Active Directory 控制台应用程序中的 Nuget 包 Microsoft.Graph.Auth 问题 - Unable to resolve Nuget package Microsoft.Graph.Auth issue in C# Active Directory console app 如何使用C#中的Azure Active Directory Graph客户端创建角色分配? - How to create role assignments using Azure Active Directory Graph client in C#? 使用http post请求使用Graph API在Azure Active Directory(B2C)中创建新用户 - Create a new user in Azure Active Directory (B2C) with Graph API, using http post request 无效的域名 Azure 活动目录问题和迁移到 Microsoft Graph C# 应用程序 - Invalid domain name Azure Active directory issue and Migration to Microsoft Graph C# application 如何使用 Microsoft Graph api 从 azure 活动目录中获取所有用户属性 - How to get all user attributes from azure active directory using Microsoft Graph api 无法使用带有中文字符Json数据的Azure Active Directory B2C Graph API创建新用户 - Unable to create new user using Azure Active Directory B2C Graph API with chinese character Json data 在.NET中创建Active Directory用户(C#) - Create Active Directory user in .NET (C#) 在 Azure Active Directory 控制台代码 C# 中获取响应的问题 - Issue in getting response in Azure Active Directory console code C# Azure Active Directory令牌缓存C#控制台应用程序 - Azure Active Directory Token Cache C# Console Application 如何使用图形API在Azure活动目录中添加外部用户 - How to add the external user in azure active directory using graph api
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM