创建允许重试 Windows 服务的机密客户端应用程序的正确方法



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

图形客户端的最新版本允许使用 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();

但是我不知道如何根据最近从"使用中间件选项的请求上下文"中的更改创建ConfidentialClientApplication

因为我无法找到最新的示例,所以我的问题是,我应该如何创建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 的新手,所以我想避免糟糕的代码。

我相信

您缺少的难题之一是此处 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 之间切换时,才需要这样做。

相关内容

最新更新