簡體   English   中英

SignInManager.PasswordSignInAsync() 成功,但 User.Identity.IsAuthenticated 為 false

[英]SignInManager.PasswordSignInAsync() succeeds, but User.Identity.IsAuthenticated is false

我是 ASP.Net Core 的新手,正在嘗試創建用戶身份驗證系統。 我正在使用 ASP.Net Core Identity 用戶管理。 我有以下用於登錄用戶的代碼。

/Areas/Identity/Pages/Account/Login.cshtml.cs

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
    returnUrl = returnUrl ?? Url.Content("~/");

    if (ModelState.IsValid)
    {
        // This doesn't count login failures towards account lockout
        // To enable password failures to trigger account lockout, set lockoutOnFailure: true
        var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);

        if (result.Succeeded)
        {
            _logger.LogInformation("User logged in.");
            _logger.LogInformation(User.Identity.IsAuthenticated.ToString());

            return LocalRedirect(returnUrl);
        }
        if (result.RequiresTwoFactor)
        {
            return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
        }
        if (result.IsLockedOut)
        {
            _logger.LogWarning("User account locked out.");
            return RedirectToPage("./Lockout");
        }
        else
        {
            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
            return Page();
        }
    }

    // If we got this far, something failed, redisplay form
    return Page();
}

啟動.cs

public void ConfigureServices(IServiceCollection services)
{
    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;
    });

    services.AddDbContext<ApplicationDbContext>(options =>
    {
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
    });

    services.AddDefaultIdentity<IdentityUser>().AddEntityFrameworkStores<ApplicationDbContext>();

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    // Use a unique identity cookie name rather than sharing the cookie across applications in the domain.
    services.ConfigureApplicationCookie(options =>
    {
        options.Cookie.Name = Configuration["CookieName"];
    });

    // Add SAML SSO services.
    services.AddSaml(Configuration.GetSection("SAML"));

    services.AddTransient<IPasswordHasher<IdentityUser>, CustomPasswordHasher>();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();

    app.UseAuthentication();

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

當用戶登錄時,我需要在 cookies 中設置一些屬性,但我總是得到User.Identity.IsAuthenticated false即使它顯示User logged in記錄器中登錄並且PasswordSignInAsync成功。 如何在OnPostAsync中登錄用戶?

注意: PasswordSignInAsync成功后重定向到主頁時用戶已登錄。

我已經檢查過這個問題,但它並沒有解決我的問題。

對於User.Identity.IsAuthenticated ,它僅適用於PasswordSignInAsync之后的子請求。

您可以嘗試以下選項:

  1. 重定向到另一個操作來設置 cookie。

     public class LoginModel : PageModel { private readonly SignInManager<IdentityUser<int>> _signInManager; private readonly ILogger<LoginModel> _logger; public LoginModel(SignInManager<IdentityUser<int>> signInManager, ILogger<LoginModel> logger) { _signInManager = signInManager; _logger = logger; } //rest code public async Task<IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true); if (result.Succeeded) { _logger.LogInformation("User logged in."); return LocalRedirect($"~/Identity/Account/Login?handler=SetIdentity&returnUrl={returnUrl}"); } if (result.RequiresTwoFactor) { return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe }); } if (result.IsLockedOut) { _logger.LogWarning("User account locked out."); return RedirectToPage("./Lockout"); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return Page(); } } // If we got this far, something failed, redisplay form return Page(); } public async Task<IActionResult> OnGetSetIdentityAsync(string returnUrl) { _logger.LogInformation(User.Identity.IsAuthenticated.ToString()); return LocalRedirect(returnUrl); } }
  2. 使用_signInManager.CreateUserPrincipalAsync

     public async Task<IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true); if (result.Succeeded) { var user = await _signInManager.UserManager.FindByEmailAsync(Input.Email); var userPrincipal = await _signInManager.CreateUserPrincipalAsync(user); var identity = userPrincipal.Identity; return LocalRedirect(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe }); } if (result.IsLockedOut) { _logger.LogWarning("User account locked out."); return RedirectToPage("./Lockout"); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return Page(); } } // If we got this far, something failed, redisplay form return Page(); }

只是為未來的搜索者回答。
以前遇到過這個問題。

我的問題是登錄后身份的 Cookie 存在於瀏覽器中,但應用程序無法讀取它,我只是添加了兩個app.UseAuthorization(); app.UseAuthentication(); 到我的 program.cs 然后我讀了 Cookies 就好了。

    [HttpPost]
    public async Task<IActionResult> Login(string username,string password)
    {
        if (User.Identity.IsAuthenticated)
        {
            return Redirect("/");
        }

        if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(username))
        {
            var result = await signInManager.PasswordSignInAsync(username, password, true,false);
            if (!result.Succeeded)
            {
                ModelState.AddModelError("Wrong", "Username or Password are wrong");
            }
            else {
                return Redirect("/");
            }
        }
        else {
            ModelState.AddModelError("Cant Be Empty", "username and password can not be empty.");
        }
        return View();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM