成功登录后 HttpContext.User.Claims 和 IHttpContextAccessor 都返回空值 [英] HttpContext.User.Claims and IHttpContextAccessor both returns empty value after successful login

查看:18
本文介绍了成功登录后 HttpContext.User.Claims 和 IHttpContextAccessor 都返回空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HttpContext.User.Claims 和 IHttpContextAccessor 在 .NET Core 2.2 成功登录后都返回空值这是我的启动服务,

HttpContext.User.Claims and IHttpContextAccessor both returns empty value after successful login in .NET Core 2.2 Here my Startup Services,

  services.AddDbContext<ApplicationDbContext>(options =>
              options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")
                     ,b=>b.MigrationsAssembly("AdaptiveBizapp")));

            services.AddDbContext<Project_Cost_Management_SystemContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("Project_Cost_Management_SystemContext") 
                    , b => b.MigrationsAssembly("AdaptiveBizapp")));

            services.AddDefaultIdentity<ApplicationUser>()
                .AddRoles<ApplicationRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                 .AddDefaultTokenProviders();

            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;

            });
            services.ConfigureApplicationCookie(options => {
                options.LoginPath = "/Account/login";
                options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;                
                });
            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                // Set a short timeout for easy testing.
                options.IdleTimeout = TimeSpan.FromMinutes(30);
                options.Cookie.HttpOnly = true;
                // Make the session cookie essential
                options.Cookie.IsEssential = true;
            });
 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); 

和我的配置部分,

 app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy(); 

            app.UseSession();

            app.UseAuthentication(); 
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
                routes.MapRoute(
             name: "area",
             template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
            });

我使用了基于身份和角色的授权.登录成功后,在 HomeController 中,当我读取用户声明或 NameIdentifier 为空时.但是当我在同一个 LoginController 中读取它时,它在 ClaimPrincipal 中具有价值,

I used Identity and Role based authorization. After login successful, in HomeController when i read user claims or NameIdentifier is empty. But when i read in same LoginController It has value at ClaimPrincipal,

  public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
        {
            var principal =await base.CreateAsync(user);

            // Add your claims here
            ((ClaimsIdentity)principal.Identity).
               AddClaims(new[] {
         new System.Security.Claims.Claim(ClaimTypes.NameIdentifier,
            user.UserName.ToString()) 
            });


            return principal;
        }

推荐答案

如果你想对 IHttpContextAccessor 使用依赖注入,你需要添加:

if you want use Depency Injection for IHttpContextAccessor you need to add :

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
        ...
        services.AddHttpContextAccessor();
        services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        ...
        }
    }

这篇关于成功登录后 HttpContext.User.Claims 和 IHttpContextAccessor 都返回空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆