代码:TokenNotFound 消息:在令牌缓存中找不到用户.可能服务器重启了

Code: TokenNotFound Message: User not found in token cache. Maybe the server was restarted(代码:TokenNotFound 消息:在令牌缓存中找不到用户.可能服务器重启了)
本文介绍了代码:TokenNotFound 消息:在令牌缓存中找不到用户.可能服务器重启了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有以下功能从活动目录调用用户使用图形 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 消息:在令牌缓存中找不到用户.可能服务器重启了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to MOQ an Indexed property(如何最小起订量索引属性)
Mocking generic methods in Moq without specifying T(在 Moq 中模拟泛型方法而不指定 T)
How Moles Isolation framework is implemented?(Moles Isolation 框架是如何实现的?)
Difference between Dependency Injection and Mocking Framework (Ninject vs RhinoMocks or Moq)(依赖注入和模拟框架之间的区别(Ninject vs RhinoMocks 或 Moq))
How to mock Controller.User using moq(如何使用 moq 模拟 Controller.User)
How do I mock a class without an interface?(如何模拟没有接口的类?)