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

时间:2019-03-29 01:04:13

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

我在数据库中有一个表,其中包含电子邮件以及多个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;

1 个答案:

答案 0 :(得分: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;