TokenNotFound消息:在令牌缓存中找不到用户。也许服务器已重新启动

问题描述 投票:1回答:1

我具有以下功能,可以从活动目录使用图形API调用用户。在文本框的每个快捷键上都单击此功能。但是我收到以下错误

代码:TokenNotFound消息:在令牌缓存中找不到用户。也许服务器已重新启动。

在此代码行中

var user = await graphClient.Users.Request().GetAsync();

我的班

 public class GraphSdkHelper : IGraphSdkHelper
    {
        private readonly IGraphAuthProvider _authProvider;
        private GraphServiceClient _graphClient;

        public GraphSdkHelper(IGraphAuthProvider authProvider)
        {
            _authProvider = authProvider;
        }

        // Get an authenticated Microsoft Graph Service client.
        public GraphServiceClient GetAuthenticatedClient(ClaimsIdentity userIdentity)
        {
            _graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(
                async requestMessage =>
                {
                    // Get user's id for token cache.
                    var identifier = userIdentity.FindFirst(Startup.ObjectIdentifierType)?.Value + "." + userIdentity.FindFirst(Startup.TenantIdType)?.Value;

                    // Passing tenant ID to the sample auth provider to use as a cache key
                    var accessToken = await _authProvider.GetUserAccessTokenAsync(identifier);

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

                    // This header identifies the sample in the Microsoft Graph service. If extracting this code for your project please remove.
                    requestMessage.Headers.Add("SampleID", "aspnetcore-connect-sample");
                }));

            return _graphClient;
        }
    }
    public interface IGraphSdkHelper
    {
        GraphServiceClient GetAuthenticatedClient(ClaimsIdentity userIdentity);
    }
}

Starup班

   public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        public const string ObjectIdentifierType = "http://schemas.microsoft.com/identity/claims/objectidentifier";
        public const string TenantIdType = "http://schemas.microsoft.com/identity/claims/tenantid";

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            }).AddAzureAd(options => Configuration.Bind("AzureAd", options)).AddCookie();

            services.AddControllersWithViews();
            services.AddRazorPages();

            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromSeconds(10);
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;
            });

            // Add application services.
            //services.AddSingleton<IConfiguration>(Configuration);
            services.AddSingleton<IGraphAuthProvider, GraphAuthProvider>();
            services.AddTransient<IGraphSdkHelper, GraphSdkHelper>();

            //Connection string 
            services.AddDbContext<PFEContext>(options => options.UseSqlServer(Configuration.GetConnectionString("PFEContext")));

            //Group authorization 
            services.AddAuthorization(options => options.AddPolicy("Customer", policyBuider =>
                policyBuider.RequireClaim("groups", "fb721f47-a58c-450a-9fbd-ff13f5960049")));
            services.AddAuthorization(options => options.AddPolicy("Developper", policyBuider =>
                policyBuider.RequireClaim("groups", "4fad5c4d-9bf9-477b-8814-02dffea5f102")));
            services.AddAuthorization(options => options.AddPolicy("ProjectManager", policyBuider =>
                policyBuider.RequireClaim("groups", "635b3fff-bb39-4726-8d76-1fef66fb2e8c")));
            services.AddAuthorization(options => options.AddPolicy("Tester", policyBuider =>
                policyBuider.RequireClaim("groups", "484d8c6c-f458-422f-9e0a-66a971874f3c")));



        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {


            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();
            app.UseCookiePolicy();
            app.UseSession();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }
    }

我需要同样的帮助来解决此问题,出了什么问题?

c# .net asp.net-core azure-active-directory azure-ad-graph-api
1个回答
0
投票

我认为这可能是由于令牌未能很好地保留在内存缓存中,

否则,也许您在关闭浏览器时正在重新启动应用程序,所以您需要在VS中禁用此选项,因为在重新启动应用程序时,它会清除内存中的所有临时数据。

您可以按照以下步骤禁用此功能:

进入工具-> 选项,然后导航到项目和解决方案-> Web项目取消选中选项停止调试器,当浏览器时窗口关闭

© www.soinside.com 2019 - 2024. All rights reserved.