ASP.NET Core MVC Interview Question #107

How do you sign a user in with cookie authentication?

Authentication, Authorization, Security & State Management Mid-Level Intermediate

Quick Interview Answer

After validating the user's credentials, create a ClaimsIdentity and ClaimsPrincipal and call SignInAsync with the configured authentication scheme. The authentication handler creates the protected cookie.

Detailed Explanation

After validating the user's credentials, create a ClaimsIdentity and ClaimsPrincipal and call SignInAsync with the configured authentication scheme. The authentication handler creates the protected cookie.

Never create the authentication principal before credentials have been securely verified. In applications using ASP.NET Core Identity, prefer Identity's SignInManager rather than reimplementing credential and cookie management.

Code Example

var claims = new[]
{
    new Claim(ClaimTypes.NameIdentifier, user.Id),
    new Claim(ClaimTypes.Name, user.Email)
};

var identity = new ClaimsIdentity(
    claims, "AppCookie");

await HttpContext.SignInAsync(
    "AppCookie",
    new ClaimsPrincipal(identity));