我怎样才能获得刷新令牌

时间:2017-03-21 07:24:07

标签: azure-active-directory adal

我学习了这个代码示例:https://github.com/Azure-Samples/active-directory-dotnet-graphapi-web,是的,我可以在AuthorizationCodeReceived中获取访问令牌:     AuthenticationHelper.token = result.AccessToken;

但是如何获得刷新令牌?result.RefreshToken不可用,那么我如何使用acquiretokenbyrefreshtoken函数?

https://msdn.microsoft.com/en-us/library/microsoft.identitymodel.clients.activedirectory.authenticationcontext.acquiretokenbyrefreshtoken.aspx

2 个答案:

答案 0 :(得分:9)

在ADAL 2.X中可以使用acquiretokenbyrefreshtoken函数,该代码示例使用ADAL 3.13.8,而ADAL3.X中,库不会公开刷新令牌和AuthenticationContext.AcquireTokenByRefreshToken函数。

ADAL缓存刷新令牌,并在您调用AcquireToken时自动使用它,并且所请求的令牌需要续订(即使您希望为不同的资源获取新的访问令牌)。

请参阅here的说明。另请单击herehere以获取有关ADAL中刷新令牌的更多详细信息。

答案 1 :(得分:2)

如果您要寻找一种持久性机制,则只需使用TokenCache.Serialize()

这是我的做法:

首先,获取令牌并序列化缓存令牌

AuthenticationContext authContext = new AuthenticationContext($"https://login.microsoftonline.com/{Tenant}");
var authResult = authContext.AcquireTokenAsync(resource, ClientId, new Uri("https://login.microsoftonline.com/common/oauth2/nativeclient"), new PlatformParameters(PromptBehavior.SelectAccount)).Result;
byte[] blobAuth = authContext.TokenCache.Serialize();

然后,加载缓存的字节

AuthenticationContext authContext = new AuthenticationContext($"https://login.microsoftonline.com/{tenant}/");
authContext.TokenCache.Deserialize(blobAuth);
var res = authContext.AcquireTokenSilentAsync(resource, clientId).Result;