创建允许重试Windows服务的ConfidentialClientClientApplication的正确方法

时间:2019-04-08 10:50:22

标签: c# microsoft-graph microsoft-graph-sdks microsoft-graph-mail

我正在尝试创建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 Options的最新更改来创建ConfidentialClientApplication

因为我找不到最新的例子,我的问题是,我应该如何创建GraphServiceClient才能从Windows Service发送电子邮件?

这是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的新手,所以我想避免不良代码。

1 个答案:

答案 0 :(得分: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之间切换的情况下才需要。