仅使用带有C#的email / refresh_token获取访问令牌

问题描述 投票:1回答:1

我在数据库中有一个表,其中包含电子邮件及其多个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;
c# microsoft-graph msal microsoft-graph-sdks
1个回答
1
投票

我相信你正在寻找使用Microsoft.Identity.Client -Version 3.0.2-preview的AcquireTokenByRefreshTokenAsync

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

AuthenticationResult result = (cca as IByRefreshToken).
    AcquireTokenByRefreshTokenAsync(scopes, refreshToken)
   .Result;
© www.soinside.com 2019 - 2024. All rights reserved.