繁体   English   中英

User.Identity 始终为 null

[英]User.Identity is always null

我需要检查用户是否登录。 在视图中,我正在像这样检查它;

                @if (User.Identity.IsAuthenticated)
                {
                    //links...
                }
                else
                {
                    //links...
                }

尽管我在登录 function 中进行了 SignInAsync,但始终返回 false 并且 Identity 为空。 我试图更改配置方法 usings 的顺序,但没有奏效。 这是我的启动和登录 function。

 public void ConfigureServices(IServiceCollection services)
    {
        var key = Encoding.ASCII.GetBytes(Configuration.GetSection("Appsettings:Secret").Value);
        services.AddDbContext<BiHaberContext>();
        services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<BiHaberContext>()
            .AddDefaultTokenProviders();
        services.Configure<IdentityOptions>(options =>
        {
            options.Password.RequireDigit = false;
            options.Password.RequiredLength = 3;
            options.Password.RequireLowercase = false;
            options.Password.RequireUppercase = false;
            options.Password.RequireNonAlphanumeric = false;
            options.Lockout.MaxFailedAccessAttempts = 3;
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);

            options.User.RequireUniqueEmail = false;
            options.SignIn.RequireConfirmedEmail = false;
            options.SignIn.RequireConfirmedPhoneNumber = false;
            options.SignIn.RequireConfirmedAccount = false;
        });

        services.AddAutoMapper(typeof(Startup));


        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                //options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan = TimeSpan.FromDays(30);
                options.LoginPath = "/Login";
                options.AccessDeniedPath = "/Identity/Account/AccessDenied";
                options.SlidingExpiration = true;
            });

        services.AddAuthentication();
        services.AddAuthorization();
        services.AddControllersWithViews();
        services.AddScoped<ISemesterService, SemesterManager>();
        services.AddScoped<IDepartmentService, DepartmentManager>();
        services.AddScoped<ICourseService, CourseManager>();
        services.AddScoped<IAnnouncementService, AnnouncementManager>();
        services.AddCors();
        services.AddResponseCaching();
        services.AddMemoryCache();

    }

    // 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");
            app.UseHsts();
        }
        app.UseCors(x => x.AllowAnyHeader().AllowAnyOrigin().AllowAnyHeader());
        app.UseResponseCaching();
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseCookiePolicy();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}");
        });
    }

登录:

 [HttpPost("/login")]
    public async Task<IActionResult> Login(LoginModel model)
    {
        if (!ModelState.IsValid)
            return View(model);

        var myContent = JsonConvert.SerializeObject(model);
        var stringContent = new StringContent(myContent, System.Text.Encoding.UTF8, MediaTypeNames.Application.Json);
        using (var postTask = await ApiHelper.ApiClient.PostAsync("Auth/Login", stringContent))
        {
            string jwt = await postTask.Content.ReadAsStringAsync();
            var handler = new JwtSecurityTokenHandler();
            var token = handler.ReadJwtToken(JwtExtension.CorrectJwtFormat(jwt));
            var claims = token.Payload.Claims.ToList();
            var claimsIdentity = new ClaimsIdentity(
                claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var authProperties = new AuthenticationProperties()
            {
                AllowRefresh = true, ExpiresUtc = DateTimeOffset.Now.AddMonths(1), IsPersistent = true
            };
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsIdentity),authProperties);
            return RedirectToAction("index", "home");
        }
    }

API 运行良好,给我带来了 7 个声明,claimIdentity 也包含它们。 并重定向到索引。 我做错了什么我只是想不通。 补充:我也不能使用 Authorize 属性。 所以在任何地方都没有授权。

当我删除这一行

            services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<BiHaberContext>();

有效。 身份高于我自己的主张。 感谢@David Liang

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM