Search code examples
c#authenticationasp.net-core-mvcasp.net-core-identity

UserIdentity is null after successful login and redirection to another razor view, ASP.NET Core MVC web application


This is the first time that I'm using the default IdentityUser to let users register and login into the application.

  • ASP.NET Core 6
  • Microsoft.AspNetCore.Identity
  • Microsoft Entity Framework Core

Configuration is

builder.Services.AddIdentity<IdentityUser, IdentityRole>(options =>
{
    // configure options for identity user
    options.Password.RequiredLength = 10;
    options.Password.RequireDigit = true;
    options.Password.RequireNonAlphanumeric = false;
    options.SignIn.RequireConfirmedEmail = false;
    options.SignIn.RequireConfirmedPhoneNumber = false;
    // Default User settings.
    options.User.AllowedUserNameCharacters =
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
options.User.RequireUniqueEmail = false;
})
.AddEntityFrameworkStores<ApplicationDBContext>();

App configuration

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();

app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");

and in the controller I have

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginModel loginUser) 
{
    if (!ModelState.IsValid) 
    {
        return View(loginUser);
    }   

    var result = await _signinManager.PasswordSignInAsync(loginUser.Email,loginUser.Password, 
        isPersistent: false, false);  

    if (result.Succeeded) 
    {
        return RedirectToAction("Index", "Home");
    }

    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
    // TODO: log error

    return View();
}

The result is Succeeded and I redirect to Home/Index right after successful login.

The cookie is created and I can see that in the development console in my browser.

In the HomeController I have

[HttpGet]
public IActionResult Index() 
{
    var loginUser = User.Identity.Name;

    MyEntity obj = new MyEntity ();
    return View(obj);
}

but loginUser is always null.

Also, when I try to use the User in _layout to display the login user, it's also null.

Most of the answers here are to redirect right after signing to be able to get the user, but I always get a null user even after redirecting to another view.


Solution

  • I think you must add app.UseAuthentication(); before app.UseAuthorization(); in Program.cs on App configuration section.