問題描述
我有以下功能從活動目錄調用用戶使用圖形 api.此功能在文本框的每個鍵上都被擊中.但我收到以下錯誤
I have the following function to call users from active directory use graph api. This function is hit on each keyup of a text box. But i am getting following error
代碼:TokenNotFound 消息:在令牌緩存中找不到用戶.也許服務器已重新啟動.
Code: TokenNotFound Message: User not found in token cache. Maybe the server was restarted.
排隊
var user = await graphClient.Users.Request().GetAsync();
整個函數如下:
public async Task<string> GetUsersJSONAsync(string textValue)
{
// email = email ?? User.Identity.Name ?? User.FindFirst("preferred_username").Value;
var identifier = User.FindFirst(Startup.ObjectIdentifierType)?.Value;
var graphClient = _graphSdkHelper.GetAuthenticatedClient(identifier);
string usersJSON = await GraphService.GetAllUserJson(graphClient, HttpContext, textValue);
return usersJSON;
}
public static async Task<string> GetAllUserJson(GraphServiceClient graphClient, HttpContext httpContext, string textValue)
{
// if (email == null) return JsonConvert.SerializeObject(new { Message = "Email address cannot be null." }, Formatting.Indented);
try
{
// Load user profile.
var user = await graphClient.Users.Request().GetAsync();
return JsonConvert.SerializeObject(user.Where(u => !string.IsNullOrEmpty(u.Surname) && ( u.Surname.ToLower().StartsWith(textValue) || u.Surname.ToUpper().StartsWith(textValue.ToUpper()))), Formatting.Indented);
}
catch (ServiceException e)
{
switch (e.Error.Code)
{
case "Request_ResourceNotFound":
case "ResourceNotFound":
case "ErrorItemNotFound":
//case "itemNotFound":
// return JsonConvert.SerializeObject(new { Message = $"User '{email}' was not found." }, Formatting.Indented);
//case "ErrorInvalidUser":
// return JsonConvert.SerializeObject(new { Message = $"The requested user '{email}' is invalid." }, Formatting.Indented);
case "AuthenticationFailure":
return JsonConvert.SerializeObject(new { e.Error.Message }, Formatting.Indented);
case "TokenNotFound":
await httpContext.ChallengeAsync();
return JsonConvert.SerializeObject(new { e.Error.Message }, Formatting.Indented);
default:
return JsonConvert.SerializeObject(new { Message = "An unknown error has occured." }, Formatting.Indented);
}
}
}
// Gets an access token. First tries to get the access token from the token cache.
// Using password (secret) to authenticate. Production apps should use a certificate.
public async Task<string> GetUserAccessTokenAsync(string userId)
{
_userTokenCache = new SessionTokenCache(userId, _memoryCache).GetCacheInstance();
var cca = new ConfidentialClientApplication(
_appId,
_redirectUri,
_credential,
_userTokenCache,
null);
if (!cca.Users.Any()) throw new ServiceException(new Error
{
Code = "TokenNotFound",
Message = "User not found in token cache. Maybe the server was restarted."
});
try
{
var result = await cca.AcquireTokenSilentAsync(_scopes, cca.Users.First());
return result.AccessToken;
}
// Unable to retrieve the access token silently.
catch (Exception)
{
throw new ServiceException(new Error
{
Code = GraphErrorCode.AuthenticationFailure.ToString(),
Message = "Caller needs to authenticate. Unable to retrieve the access token silently."
});
}
}
你能幫忙看看出了什么問題嗎?
Can you help whats going wrong?
推薦答案
我知道這已經 4 個月大了 - 這對你來說仍然是個問題嗎?
I know this is 4 months old - is this still an issue for you?
正如之前的受訪者所指出的,您看到的錯誤是在您的代碼中的 catch 塊中拋出的,該代碼用于處理空的 users 集合.
As the previous respondent pointed out, the error you're seeing is being thrown in the catch block in your code meant to handle an empty users collection.
如果你被困在這個問題上,或者其他人來這里 - 如果你使用 this sample (或在任何方面使用 ConfidentialClientApplication
)并拋出此異常,這是因為您的 _userTokenCache 沒有用戶*.當然不是因為你的AD沒有用戶,否則你就無法認證.很可能是因為您的瀏覽器中的一個陳舊的 cookie 作為訪問令牌傳遞給您的 authProvider.您可以使用 Fiddler(或僅檢查您的 localhost 瀏覽器 cookie)來找到它(應該稱為 AspNetCore.Cookies,但您可能需要清除所有這些).
In case you're stuck on this, or anyone else comes here - if you used this sample (or using ConfidentialClientApplication
in any respect) and are throwing this exception, it's because your _userTokenCache has no users*. Of course, it's not because your AD has no users, otherwise you wouldn't be able to authenticate. Most likely, it is because a stale cookie in your browser is being passed as the access token to your authProvider. You can use Fiddler (or just check your localhost browser cookies) to find it (should be called AspNetCore.Cookies, but you may want to clear all of them).
如果您將令牌緩存存儲在會話中(如示例所示),請記住,每次啟動和停止應用程序時,您的工作內存都會被丟棄,因此您的瀏覽器提供的令牌將不再匹配新的您的應用程序將在重新啟動時檢索到的一個(除非您再次清除了瀏覽器 cookie).
If you're storing the tokencache in session (as the example is), remember that each time you start and stop the application, your working memory will be thrown out so the token provided by your browser will no longer match the new one your application will retrieve upon starting up again (unless, again, you've cleared the browser cookies).
*cca.Users
- 您必須使用 cca.GetAccountsAsync()
.如果您的已部署應用程序使用已棄用的 IUser
實現運行,則必須更改此設置.否則,在開發過程中,您的編譯器會抱怨并且不允許您構建,所以您已經知道了這一點.
*cca.Users
is no longer used or supported by MSAL - you have to use cca.GetAccountsAsync()
. If you have a deployed application running with the deprecated IUser
implementation, you'll have to change this. Otherwise, in development your compiler will complain and not let you build, so you'll already know about this.
這篇關于代碼:TokenNotFound 消息:在令牌緩存中找不到用戶.可能服務器重啟了的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!