1

我正在使用以下代码对 Dynamics 进行身份验证:

public async Task<String> GetAuthenticationToken(string uri, string clientId, string clientSecret)
{
AuthenticationParameters ap = 
AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(uri)).Result;
var creds = new ClientCredential(clientId, clientSecret);
AuthenticationContext authContext = new AuthenticationContext(ap.Authority);
AuthenticationResult result = await 
authContext.AcquireTokenAsync(ap.Resource, creds);
return result.AccessToken;
}

它工作得很好,并返回一个 AuthenticationResult ,其中包括:

AccessToken: The usual long string
AccessTokenType : Bearer
ExpiresOn : DateTime 1 hour from now
ExtendedExpiresOn : Datetime 3 days from now
Authority : A login.microsoft.com URL

问题是我不知道如何刷新令牌以便我可以继续工作。是否有一个简单的电话可以让我再延长一个小时?

4

1 回答 1

1

你可以做这样的事情,不是 100% 确定代码,还没有测试

 private static string GetToken(TraceWriter log)
    {
        lock (tokenlock)
        {
            if (DateTime.UtcNow >= ExpireDate)
            {

                var clientcred = new ClientCredential(clientId, clientSecret);
                AuthenticationContext authContext = new AuthenticationContext(aadInstance, false);
                AuthenticationResult result = authContext.AcquireToken(organizationUrl, clientcred);
                token = result.AccessToken;
                ExpireDate = result.ExpiresOn.DateTime;
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
            }
            return token;
        }
    }
于 2018-09-21T07:08:51.913 回答