首页 > 解决方案 > 即使在 asp.net core 2.2 中使用 PasswordSignInAsync 成功登录后,User.Identity.IsAuthenticated 也总是返回 false

问题描述

每当我点击登录时,用户都会使用 signinManager.PasswordSignInAsync 登录,并且 result.Succeeded 为真。问题是,如果我第二次调用登录,用户不会坚持。User.Identity.IsAuthenticated 下次应该为真,但始终为假

 [HttpGet("[action]")]
    public async Task<IActionResult> Login()
    {
        try
        {
            if (User.Identity.IsAuthenticated)
            {
                Console.WriteLine("You are alredy Logged In...................");
                var claims = User.Claims;
                return Ok("Authenticated");

            }
            else
            {


                var result = await signinManager.PasswordSignInAsync("myEmail.com", "Password", true, true);
                if (result.Succeeded)
                {

                    Console.WriteLine("Logged in successfully....");

                }
                return Ok("Logged in successfully ");
            }


        }
        catch (System.Exception e)
        {
            Console.WriteLine("........................................" +e.Message);
            return Ok(e.Message);
            throw;
        }


    }

StartUp.Cs 中的 ConfigureServices 看起来像

   public void ConfigureServices(IServiceCollection services)
    {

        services.AddDbContext<DbContextBase>(options =>
   options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddIdentity<AppUser, IdentityRole>()
    .AddEntityFrameworkStores<DbContextBase>()
    .AddDefaultTokenProviders();


        services.AddMvc();
    }

Startup.cs 中的配置方法如下所示:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
            {
                HotModuleReplacement = true
            });
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();
        app.UseAuthentication();

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

            routes.MapSpaFallbackRoute(
                name: "spa-fallback",
                defaults: new { controller = "Home", action = "Index" });
        });
    }

登录方法在第二次点击时必须返回“Authenticated”。

标签: c#.net-coreasp.net-core-identity

解决方案


您忘记配置实际的身份验证方法,例如 cookie。

在你的ConfigureServices

services.ConfigureApplicationCookie(options =>
{
    // Cookie settings
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(5);

    options.LoginPath = "/Identity/Account/Login";
    options.AccessDeniedPath = "/Identity/Account/AccessDenied";
    options.SlidingExpiration = true;
});

推荐阅读