无法使用 Microsoft Graph 找到刷新令牌

Unable to locate the refresh token with Microsoft Graph

我正在寻找 here 关于 刷新令牌

我有这个代码来获取访问令牌:

if(bPromptUser)
{
    _AuthResult = await PublicClientApp.AcquireTokenAsync(_scopes); //Opens Microsoft Login Screen

    using (RegistryKey key = Registry.CurrentUser.CreateSubKey(keyName))
    {
        key.OpenSubKey(keyName, true);
        key.SetValue("Status", _AuthResult.AccessToken);
        key.SetValue("Expire", _AuthResult.ExpiresOn.ToLocalTime().ToString());
        key.Close();

        token = _AuthResult.AccessToken;
    }

    // Append the access token to the request.
    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
}

但是我的 _AuthResult 实际上在列表中没有 RefreskToken。这是因为我使用的是 Microsoft Graph 的 v1?

更新

根据文档,答案中建议的范围默认启用?

我相信在使用 MSAL(和 v2 身份验证端点)时,默认情况下您不会获得刷新令牌。要获取刷新令牌,您需要请求 offline_access 范围以及其他范围。请参阅 https://developer.microsoft.com/en-us/graph/docs/concepts/permissions_reference#openid-permissions 了解更多详情。

希望对您有所帮助,

Microsoft 为 TokenCacheHelper.

提供示例代码

将其添加到您的项目中并提供它的一个实例。然后,设置路径。像这样:

TokenCacheHelper.CacheFilePath = Program.Options.TokenCachePath;
PublicClientApp = new PublicClientApplication(_AppID, "https://login.microsoftonline.com/common", TokenCacheHelper.GetUserCache());

这就是您需要做的全部。缓存文件包含所有令牌详细信息,包括刷新令牌。

对话中有更多详细信息here。部分:

As far as helping you to implement the token cache, to store the content of the token cache, you need to:

  1. Copy the TokenCacheHelper from here to your project.
  2. If you really want to save the content of the cache to the registry, change the implementation of:
    • AfterAccessNotification to write to the registry instead of a file this line
    • BeforeAccessNotification to read fromthe registry instead of a file this line
  3. Construct the PublicClientApplication your as shown here (passing the cache that you get by calling TokenCacheHelper.GetUserCache(): https://github.com/Azure-Samples/active-directory-dotnet-desktop-msgraph-v2/blob/master/active-directory-wpf-msgraph-v2/App.xaml.cs#L19:

    clientApp = new PublicClientApplication(ClientId, "https://login.microsoftonline.com/common", TokenCacheHelper.GetUserCache());

对我来说,我的问题是使用旧版本的 Microsoft.Identity.Client nuget 包。从 4.35.1 升级到 4.40.0 修复了令牌错误。