即使在asp.net core 2.2中使用PasswordSignInAsync成功登录后,User.Identity.IsAuthenticated也始终返回false。

时间:2019-05-12 12:07:34

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

每当我单击“登录”时,就使用signinManager.PasswordSignInAsync登录用户,并且result.Succeeded为true。问题是,如果我第二次致电登录,则该用户将无法使用。下次User.Identity.IsAuthenticated应该为true,但始终为

 [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中的Configure Method如下:

 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”。

2 个答案:

答案 0 :(得分:0)

要检查用户是否已通过身份验证,可以使用

public UserService(
            IHttpContextAccessor httpContextAccessor)
{
    _httpContextAccessor = httpContextAccessor;
}

public bool IsAuthenticated()
{
    return _httpContextAccessor.HttpContext.User.Identity.IsAuthenticated;
}

然后在您的startup.cs中将其添加到配置cookie

    services
                .AddIdentity<User, ApplicationRole>(options =>
                {
                    options.Password.RequireDigit = false;
                    options.Password.RequiredLength = 4;
                    options.Password.RequireLowercase = false;
                    options.Password.RequireNonAlphanumeric = false;
                    options.Password.RequireUppercase = false;

                    //lock out attempt
                    options.Lockout.AllowedForNewUsers = true;
                    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
                    options.Lockout.MaxFailedAccessAttempts = 3;
                })
                .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 => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            //The default value is 14 days.
            services.ConfigureApplicationCookie(options =>
            {
                options.ExpireTimeSpan = TimeSpan.FromHours(1);
            });

如果您还有任何问题,请告诉我

答案 1 :(得分:0)

您忘记配置实际的身份验证方法,例如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;
});