将authProvider与MS SDK一起用于C#

时间:2019-05-15 15:31:54

标签: c# azure-active-directory microsoft-graph

我正在尝试创建一个C#控制台应用程序以连接到图形API,并从一个租户处从AzureAD获取用户列表。我已经注册了该应用,管理员已给我以下内容

  • 租户名称和租户ID
  • 客户端ID(有时也称为应用ID)
  • 客户秘密

使用sdk,我需要使用C#代码,如下所示(https://docs.microsoft.com/en-us/graph/api/user-list?view=graph-rest-1.0&tabs=cs):

GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var users = await graphClient.Users
    .Request()
    .GetAsync();

但是,控制台应用程序将作为批处理进程运行,因此根本没有用户交互。因此,为了提供authProvider,我在MS docs网站上关注了这篇文章:https://docs.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=CS

出于我的目的,我需要参加“客户端凭据OAuth流程”。该URL上显示的代码。但是这里也是。

IConfidentialClientApplication clientApplication = ClientCredentialProvider.CreateClientApplication(clientId, clientCredential);
ClientCredentialProvider authProvider = new ClientCredentialProvider(clientApplication);

问题在于Visual Studio无法识别ClientCredentialProvider类。我不确定要导入哪个程序集。我在顶部使用以下用法。

using Microsoft.Identity.Client;
using Microsoft.IdentityModel.Clients;
using Microsoft.IdentityModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

我对GitHub存储库不是很有经验,并且我正在使用Visual Studio2015。我会对示例代码感兴趣;我看过但找不到。 MS有一些讲座,但是他们使用另一种身份验证提供程序,它是交互式身份验证,这不是我想要的。我想使用TenantId / ClientId和Client Secret获取令牌。

2 个答案:

答案 0 :(得分:0)

ClientCredentialProvider 是Microsoft.Graph.Auth程序包的一部分。您可以在https://github.com/microsoftgraph/msgraph-sdk-dotnet-auth

上了解有关此软件包的更多信息

请注意,此软件包当前(截至2019年5月15日)处于预览状态,因此您可能要等待在生产应用程序中使用它。

或者,以下示例直接使用Microsoft Authentication Library for .NET(MSAL)通过仅应用程序身份验证来设置Microsoft Graph SDK:

// The Azure AD tenant ID or a verified domain (e.g. contoso.onmicrosoft.com) 
var tenantId = "{tenant-id-or-domain-name}";

// The client ID of the app registered in Azure AD
var clientId = "{client-id}";

// *Never* include client secrets in source code!
var clientSecret = await GetClientSecretFromKeyVault(); // Or some other secure place.

// The app registration should be configured to require access to permissions
// sufficient for the Microsoft Graph API calls the app will be making, and
// those permissions should be granted by a tenant administrator.
var scopes = new string[] { "https://graph.microsoft.com/.default" };

// Configure the MSAL client as a confidential client
var confidentialClient = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithAuthority($"https://login.microsoftonline.com/$tenantId/v2.0")
    .WithClientSecret(clientSecret)
    .Build();

// Build the Microsoft Graph client. As the authentication provider, set an async lambda
// which uses the MSAL client to obtain an app-only access token to Microsoft Graph,
// and inserts this access token in the Authorization header of each API request. 
GraphServiceClient graphServiceClient =
    new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) => {

            // Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
            var authResult = await confidentialClient
                .AcquireTokenForClient(scopes)
                .ExecuteAsync();

            // Add the access token in the Authorization header of the API request.
            requestMessage.Headers.Authorization = 
                new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
        })
    );

// Make a Microsoft Graph API query
var users = await graphServiceClient.Users.Request().GetAsync();

(请注意,此示例使用Microsoft.Identity.Client程序包的最新版本。早期版本(版本3之前)未包含 ConfidentialClientApplicationBuilder 。)

答案 1 :(得分:0)

如果您想循环用户,请使用以下代码替换var用户:

IGraphServiceUsersCollectionPage users = graphServiceClient.Users.Request().GetAsync().Result;
foreach (User user in users)
{
Console.WriteLine("Found user: " + user.Id);
}