在 C# 中仅使用 email/refresh_token 获取访问令牌

Get access token using only email/refresh_token with C#

我在数据库中有一个 table,其中包含多个 Hotmail/Outlook.com 帐户的电子邮件及其刷新令牌(没有别的)。

我正在尝试使用刷新令牌创建访问令牌,但我找不到任何使用 Microsoft.Identity.ClientMicrosoft.Graph 库来执行该操作的代码。

这是控制台应用程序中的部分代码:

static void Main(string[] args)
{
    /* other code */
    string email, refreshToken; // obtained from database
    TokenCache tokenCache = new TokenCache(); // how do i "fill" this object?

    ConfidentialClientApplication cca = new ConfidentialClientApplication(
        "appId",
        "redirectUri",
        new ClientCredential("appSecret"),
        tokenCache,
        null);

    IAccount account = cca
        .GetAccountsAsync()
        .Result
        .FirstOrDefault();

    AuthenticationResult result = cca
        .AcquireTokenSilentAsync(new string[] { "scopes" }, account)
        .Result;

    GraphServiceClient client = new GraphServiceClient("https://outlook.office.com/api/v2.0/",
        new DelegateAuthenticationProvider((requestMessage) =>
        {
            requestMessage.Headers.Authorization =
                new AuthenticationHeaderValue("Bearer", result.AccessToken);
            return Task.FromResult(0);
        }));

    var msgs = client
        .Me
        .MailFolders
        .Inbox
        .Messages
        .Request()
        .Select(m => new { m.Subject, m.ReceivedDateTime, m.From })
        .Top(10)
        .GetAsync();

    /* more stuff to do */
}

我已经能够使用 PHP 做到这一点,但现在我需要它在 .net 中做到这一点

更新:我将使用 Marc LaFleur

的答案展示完整代码
ConfidentialClientApplication cca = new ConfidentialClientApplication(
    appId,
    redirectUri,
    new ClientCredential(appSecret),
    new TokenCache(),
    null);
AuthenticationResult result = (cca as IByRefreshToken).
    AcquireTokenByRefreshTokenAsync(scopes, refreshToken).Result;

GraphServiceClient client = new GraphServiceClient(
    "https://outlook.office.com/api/v2.0/",
    new DelegateAuthenticationProvider((requestMessage) => {
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
            return Task.FromResult(0);
    }
));

var msgs = client.Me.MailFolders.Inbox.Messages.Request().
    OrderBy("receivedDateTime DESC").
    Select(m => new { m.Subject, m.ReceivedDateTime, m.From }).
    Top(10).
    GetAsync().Result;

我相信您正在寻找 AcquireTokenByRefreshTokenAsync 使用 Microsoft.Identity.Client -版本 3.0.2-预览:

ConfidentialClientApplication cca = new ConfidentialClientApplication(
    appId,
    redirectUri,
    new ClientCredential(appSecret),
    new TokenCache(),
    null);

AuthenticationResult result = (cca as IByRefreshToken).
    AcquireTokenByRefreshTokenAsync(scopes, refreshToken)
   .Result;