如何在MS Dynamics中扩展令牌

时间:2018-09-20 15:42:12

标签: dynamics-crm dynamics-crm-webapi

我正在使用以下代码向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

问题在于我不知道如何刷新令牌,以便我可以继续工作。我可以打个简单的电话再延长一个小时吗?

1 个答案:

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