首页 > 解决方案 > 对 signInManager.PasswordSignInAsync 进行故障排除

问题描述

我是 ASP.Net 的新手,我最近开始了一个项目,遵循一些教程,进展缓慢。

我卡在登录应用程序。该应用程序已经连接到本地数据库,并为“用户”(荷兰语中的 Gebruikers)提供了基本的 CRUD 功能。我想添加“管理员”角色等等,但首先,我希望用户能够登录,然后才能访问 CRUD 功能。

所以,我把[Authorize]控制器中的“用户”功能放在前面,你瞧,它被正确地重定向到登录页面。到目前为止,一切都很好。

该代码还可以正确登录用户,并将两个 cookie 传递给浏览器。但是,登录页面再次显示。

当我消除[Authorize]标签时,代码按预期工作(无需登录)。我错过了什么?

public class UsersController : Controller
{
    [Authorize]
    public IActionResult Index()
    {
        return Redirect("Gebruikers");
    }
}

public class AccountController : Controller
{
    private readonly UserManager<IdentityUser> userManager;
    private readonly SignInManager<IdentityUser> signInManager;

    public AccountController(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager)
    {
        this.userManager = userManager;
        this.signInManager = signInManager;
    }

    [HttpGet]
    public IActionResult Login(string ReturnUrl = "")
    {
        var model = new LoginViewModel { ReturnUrl = ReturnUrl };
        return View(model);
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> LoginAsync(LoginViewModel model)
    {
        // Check if valid
        if (!ModelState.IsValid)
            return View(model);

        // Get the user
        var user = await userManager.FindByEmailAsync(model.Email);
        var result = await signInManager.PasswordSignInAsync( userName: user.UserName, password: model.Password, isPersistent: model.RememberMe, lockoutOnFailure: false);

        // Check if succeeded
        if (!result.Succeeded)
        {
            ModelState.AddModelError("", "Invalid login attempt.");
            return View(model);
        }

        // Valid and Succeeded
        switch (model.ReturnUrl)
        {
            case "/Users":
            case "/Gebruikers":
                model.ReturnUrl = "Gebruikers";
                break;
            default:
                model.ReturnUrl = "Home";
                break;
        }
        return RedirectToAction("Index", model.ReturnUrl);
    }
}

public class GebruikersController : Controller
{
    // GET: Gebruikers
    [Authorize]
    public async Task<IActionResult> Index()
    {
        return View(await _context.Gebruikers.ToListAsync());
    }
}

我可以看到与这个问题有一些相似之处,但我认为它们并不相同。

标签: c#asp.net-mvcasp.net-coreauthenticationasp.net-identity

解决方案


Net core 2.1或更高版本是内置支持GDPR(通用数据保护条例)。

并且在您接受 cookie 之前,不会在浏览器中设置 cookie。

添加以下代码以忽略GDPR

services.Configure<CookiePolicyOptions>(options =>
            {
                options.ConsentCookie.IsEssential = true;//<--NOTE THIS
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
    options.Cookie.IsEssential = true;//<--NOTE THIS
    options.Cookie.HttpOnly = true;
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
    options.Cookie.SameSite = SameSiteMode.None;
    options.LoginPath = "/Account/Login";
    options.LogoutPath = "/Account/Login";
});

然后检查中间件顺序应该是这样的

app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();

推荐阅读