Asp.NET Core 2 身份验证。 SignInManager.PasswordSignInAsync() 成功,但 User.Identity.IsAuthenticated 为 false

2024-01-31

我正在关注 IdentityUser 的一些教程,我认为我的做法与教程中的完全一样,但是当我尝试登录时,即使 _signInManager 成功,我也会收到“MyIdentity:False”(带有 LogInformation),这似乎很奇怪。我尝试将用户设置为已确认,但没有结果。

我正在 Mac 上使用 Visual Studio。

以下是我注册用户的方法:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser()
        {
            UserName = model.Email,
            Email = model.Email
        };
        var result = await _userManager.CreateAsync(user, model.Password);

        if (result.Succeeded)
        {
            await _signInManager.SignInAsync(user, false);
            return this.RedirectToAction("Index", "Home");
        }
        else
        {
            foreach (var error in result.Errors)
                ModelState.AddModelError("", error.Description);
        }   
    }

    return View(model);
}

这是我尝试登录的方法:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model)
{
    if (ModelState.IsValid)
    {
        var result = await _signInManager.PasswordSignInAsync(
            model.Email,
            model.Password,
            model.RememberMe,
            lockoutOnFailure: false
        );

        if (result.Succeeded)
        {
            _logger.LogInformation("MyIdentity: " + User.Identity.IsAuthenticated);
            return this.RedirectToAction("Index", "Home");
        }

        ModelState.AddModelError("", "Invalid Login attempt.");
    }
    return View(model);
}

以下是我为其配置服务的方法:

services.AddDbContext<CmagruDBContext>(options =>
    options.UseSqlite("Data Source=Cmagru.db",
        b => b.MigrationsAssembly("Presentation")));

services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<CmagruDBContext>()
    .AddDefaultTokenProviders();

services.Configure<IdentityOptions>(options =>
{
    options.Password.RequireDigit = false;
    options.Password.RequiredLength = 3;
    options.Password.RequireLowercase = false;
    options.Password.RequireNonAlphanumeric = false;
    options.Password.RequireUppercase = false;
    options.User.RequireUniqueEmail = true;
});

services.ConfigureApplicationCookie(options =>
{
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
    options.LoginPath = "/Account/Login";
    options.AccessDeniedPath = "/Account/AccessDenied";
    options.SlidingExpiration = true;
});

我确实有app.UseAuthentication();在配置中


对于其他可能遇到此问题的人: 就我而言,我不得不简单地说app.UseAuthentication(); before app.UseMvc() in Configure()。否则,它对我不起作用。

我想我在文档中错过了这一点。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Asp.NET Core 2 身份验证。 SignInManager.PasswordSignInAsync() 成功,但 User.Identity.IsAuthenticated 为 false 的相关文章

随机推荐