尝试使用缓存的令牌时出现以下错误。我使用此处提供的列表作为示例:https://docs.microsoft.com/bs-latn-ba/azure/active-directory/develop/msal-net-acquire-token-silently
无法从“ System.Collections.Generic.IEnumerable”转换为“ Microsoft.Identity.Client.IAccount”`
static async Task<GraphServiceClient> Auth()
{
var clientApp = PublicClientApplicationBuilder.Create(ConfigurationManager.AppSettings["clientId"]).Build();
string[] scopes = new string[] { "user.read" };
string token = null;
var app = PublicClientApplicationBuilder.Create(ConfigurationManager.AppSettings["clientId"]).Build();
AuthenticationResult result = null;
var accounts = await app.GetAccountsAsync();
result = await app.AcquireTokenSilent(scopes, accounts)
.ExecuteAsync();
token = result.AccessToken;
GraphServiceClient graphClient = new GraphServiceClient(
"https://graph.microsoft.com/v1.0",
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
}));
return graphClient;
}
答案 0 :(得分:1)
引起错误的呼叫就是这个
result = await app.AcquireTokenSilent(scopes, accounts)
.ExecuteAsync();
AcquireTokenSilent
需要两个变量,IEnumerable<String>
(作用域)和string
(loginHint)。当您将loginHist
传递给一个字符串(单个帐户)时,将传递一组帐户。
var accounts = await app.GetAccountsAsync();
GetAccountsAsync()的返回类型为IEnumerable
,这就是为什么它在该调用时引发错误的原因。
在example here中,从列表中查找的帐户。
// Get the account
IAccount account = await application.GetAccountAsync(accountIdentifier).ConfigureAwait(false);
// Special case for guest users as the Guest oid / tenant id are not surfaced.
if (account == null)
{
if (loginHint == null)
throw new ArgumentNullException(nameof(loginHint));
var accounts = await application.GetAccountsAsync().ConfigureAwait(false);
account = accounts.FirstOrDefault(a => a.Username == loginHint);
}
将此行添加到您的代码中:
var accounts = await app.GetAccountsAsync();
IAccount account = accounts.FirstOrDefault(a => a.Username == loginHint); // <--- Get Account from accounts
result = await app.AcquireTokenSilent(scopes, account) // Use account instead of accounts.
.ExecuteAsync();
token = result.AccessToken;