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

时间:2017-08-10 13:11:20

标签: c# microsoft-graph

如何使用Microsoft Graph在Azure AD中创建用户而无需登录(从控制台/服务)?

它会将所有示例联系起来,以便您必须先使用AD帐户登录。

有了这个,我得到拒绝访问。

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);
    }
}

1 个答案:

答案 0 :(得分:3)

好的,就这样吧!我花了半天时间弄清楚这一点,现在它确实有效。

转到Azure门户 - > AD部分 - >注册新应用程序(Web App / API),创建新密钥并保存。

必需的权限:

  • 申请权限
    • 读取和写入目录数据
  • 委托权限(我认为这没关系)
    • 以登录用户身份访问目录
    • 阅读所有用户基本资料
    • 登录并阅读用户个人资料

然后从“必需权限”边栏选项卡单击顶部菜单中的“授予权限”,然后单击“添加”按钮。

然后代码是这样的:

  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);
    }
}