User.Identity始终为null

问题描述

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

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

尽管我在登录功能中登录了SignInAsync,但始终返回false,并且身份为空。我试图更改usings的configure方法的顺序,但是没有用。 这是我的启动和登录功能。

 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条声明,而且ClaimsIdentity也包含它们。并重定向到索引。我做错了什么我只是不知道。 补充:另外我不能使用Authorize属性。因此,任何地方都没有授权。

解决方法

当我删除此行

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

有效。身份超越了我自己的主张。感谢@David Liang

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...