1

我正在尝试创建允许我代表特定用户发送电子邮件的 Windows 服务。

Graph Client 的最新版本允许使用WithMaxRetry. 不幸的是,在创建ConfidentialClientApplication.

目前,我使用以下代码发送电子邮件而无需输入登录名和密码:

const string clientId = "foo...99a0";
const string clientSecret = "#6A...cx#$a";
const string tenant = "1c...7";
const string azureAdInstance = "https://login.microsoftonline.com/{0}";
var authority = string.Format(CultureInfo.InvariantCulture, azureAdInstance, tenant);
string[] scopes = { "https://graph.microsoft.com/.default" };

var clientCredentials = new ClientCredential(clientSecret);
var confidentialClientApplication =
    new ConfidentialClientApplication(
        clientId,
        authority,
        "https://daemon",
        clientCredentials,
        null,
        new TokenCache());

var graphClient =
    new GraphServiceClient("https://graph.microsoft.com/v1.0", 
    new DelegateAuthenticationProvider(
        async(requestMessage) =>
        {
            var result = await confidentialClientApplication
                .AcquireTokenForClientAsync(scopes);
            requestMessage.Headers.Authorization = 
                new AuthenticationHeaderValue("bearer", result.AccessToken);
        }));

var recipients = new List<Recipient>
{
    new Recipient
    {
        EmailAddress = new Microsoft.Graph.EmailAddress
        {
            Address = "test@example.com"
        }
    }
};

var email = new Message
{
    Body = new ItemBody
    {
        Content = "Works fine!",
        ContentType = BodyType.Html,
    },
    Subject = "Test",
    ToRecipients = recipients
};

await graphClient
    .Users["sender@example.onmicrosoft.com"]
    .SendMail(email, true)
    .Request()
    .PostAsync();

但我不知道如何根据Request Context With Middleware OptionsConfidentialClientApplication的最新更改来创建。

因为我无法找到最新的示例,所以我的问题是,我应该如何创建GraphServiceClient才能从 Windows 服务发送电子邮件?

这是来自上述 PR 的代码:

HttpProvider httpProvider = new HttpProvider();

var graphClient = new GraphServiceClient(appOnlyProvider, httpProvider);
graphClient.PerRequestAuthProvider = () => CreateDelegatedProvider();

var me = await graphClient.Me.Request()
    .WithScopes(string[] { "User.Read" }) // adds auth scopes
    .WithMaxRetry(5) // specifies maximum number of retries
    .WithPerRequestAuthProvider()
    .GetAsync();

我应该如何根据我的要求采用它?我是 Graph 的新手,所以我想避免错误的代码。

4

1 回答 1

1

我认为您缺少的难题之一是新的身份验证提供程序库,该库位于https://www.nuget.org/packages/Microsoft.Graph.Auth/0.1.0-preview并且有一些示例如何在此处使用这些身份验证提供程序https://github.com/microsoftgraph/msgraph-sdk-dotnet-auth

该库提供了一组基于所需 OAuth2 流的授权提供程序。在您的情况下,您应该使用 ClientCredentialsProvider 而不是 DelegateProvider。

您不需要使用 PerRequestAuthProvider。这仅适用于您希望在每次调用中在不同流或不同 appId 之间切换的场景。

于 2019-04-10T02:01:22.427 回答