How do I enable custom cookie-based authentication in ASP.NET Core?
Posted: (EET/GMT+2)
ASP.NET Core makes it straightforward to implement custom cookie-based authentication without needing the older Membership or Identity frameworks. If you want full control over login, logout, and how cookies are issued, the built-in cookie authentication handler is a great solution.
First, add the authentication services in Startup like the following:
services.AddAuthentication("MyCookie")
.AddCookie("MyCookie", options =>
{
options.LoginPath = "/account/login";
options.AccessDeniedPath = "/account/denied";
options.Cookie.Name = "myapp.auth";
});
This configures the authentication mechanism to use a custom cookied. Next, enable that authentication in the middleware pipeline:
app.UseAuthentication(); app.UseAuthorization();
To sign the user in, create a claims principal and issue the cookie:
List<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.Name, username)
};
ClaimsIdentity identity = new ClaimsIdentity(claims, "MyCookie");
ClaimsPrincipal principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync("MyCookie", principal);
Signing out is similarly simple:
await HttpContext.SignOutAsync("MyCookie");
This pattern gives you full control over roles, claims, expiration rules, and the login experience. It also works well for small internal apps where the overhead of full ASP.NET Core Identity would be unnecessary.
If you prefer to keep authentication straightforward and fully transparent, custom cookie authentication is still one of the cleanest approaches.