如何解决Microsoft Graph 令牌缺少“帐户”属性
C# 应用程序(.Net 框架 4.8)我正在处理依赖于技术用户 OneDrive 上存储的文件。文件通过 Microsoft Graph SDK 访问。身份验证是通过存储在机器上的 Msal 令牌执行的。我们还实施了观察者服务,确保令牌在到期前刷新。
最近我被指派将所有内容迁移到不同的用户,但是我正在努力获取具有我需要的所有属性的身份验证令牌。
当前存在并在应用程序中使用的令牌具有以下结构:
{
"AccessToken": {
...
}
},"RefreshToken": {
...
}
},"IdToken": {
...
}
},"Account": {
"": {
"home_account_id": "","environment": "","client_info": "","username": "","name": "","local_account_id": "","authority_type": "MSSTS","realm": ""
}
},"AppMetadata": {
"appmetadata-login.windows.net-{appId}": {
"environment": "","client_id": ""
}
}
}
当我尝试根据以下文档获取令牌时:https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
{
"token_type": "Bearer","scope": "openid profile email https://graph.microsoft.com/Files.ReadWrite.All","expires_in": 3599,"ext_expires_in": 3599,"access_token": "","refresh_token": "","id_token": ""
}
我得到的令牌没有 JSON 中的“帐户”对象/属性。问题是,我如何获取包含帐户属性的访问令牌?
通过 jwt.ms 检查访问令牌后,结果是帐户属性嵌入在访问令牌中。当我尝试通过以下代码访问帐户时,这是不可能的。具有新令牌的机密客户端应用程序不包含任何帐户。
private async Task<string> GetTokenAsync()
{
var cca = ConfidentialClientApplicationBuilder.Create(appId).WithClientSecret(appSecret).WithRedirectUri(redirectUri).Build();
GraphTokenCache.TokenFilePath = tokenFilePath;
GraphTokenCache.EnableSerialization(cca.UserTokenCache);
var accounts = await cca.GetAccountsAsync();
var account = accounts.First(); // <- Always returns 0
var result = cca.AcquireTokenSilent(new[] { "Files.ReadWrite.All" },account).ExecuteAsync().Result;
return result.AccessToken;
}
public class GraphTokenCache
{
public static string TokenFilePath;
public static void EnableSerialization(ITokenCache cache)
{
cache.SetBeforeAccess(BeforeAccessNotification);
cache.SetAfterAccess(AfterAccessNotification);
}
static void BeforeAccessNotification(TokenCacheNotificationArgs args)
{
if (System.IO.File.Exists(TokenFilePath))
{
var bytes = System.IO.File.ReadAllBytes(TokenFilePath);
args.TokenCache.DeserializeMsalV3(bytes);
}
}
static void AfterAccessNotification(TokenCacheNotificationArgs args)
{
if (args.HasStateChanged)
{
var bytes = args.TokenCache.SerializeMsalV3();
System.IO.File.WriteAllBytes(TokenFilePath,bytes);
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。