Introduction
In the previous lessons, we implemented user registration, login and logout flows. In this lesson, we will examine how a signed-in user is recognized across subsequent HTTP requests and how access to selected MVC pages can be restricted to authorized users.
Cookie Authentication is based on a server-generated authentication ticket that is sent to the client as a cookie. After a successful login, the application creates an authentication cookie. The browser automatically sends that cookie with later requests to the same application. ASP.NET Core middleware validates the cookie, creates the user principal and places it in HttpContext.User, allowing authorization rules to run.
This approach provides a natural user experience for browser-based MVC and Razor Pages applications. An unauthenticated user who requests a protected page can be redirected to the login page. A signed-in user who does not have the required role or policy can instead be sent to an access denied page.
The Authentication and Cookie Flow
Three operations are especially important in Cookie Authentication:
- Authenticate: The handler reads the cookie and creates a user principal if the cookie is valid.
- Challenge: When the user is not authenticated, the default browser-oriented behavior can redirect the request to the configured login path.
- Forbid: When the user is authenticated but lacks the required permission, the access denied behavior is used.
Applying the [Authorize] attribute to a controller or action requires an authenticated user. The [AllowAnonymous] attribute is used for actions such as login, registration or a public home page. Apply it carefully: at controller level, it can bypass authorization requirements that would otherwise apply to actions on that controller.
Configuring Cookies with Identity
When ASP.NET Core Identity is used, cookie authentication is normally configured by Identity. Instead of registering a second, unrelated cookie handler, the common approach is to customize the Identity application cookie with ConfigureApplicationCookie.
using Microsoft.AspNetCore.Identity;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.SignIn.RequireConfirmedAccount = false;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
builder.Services.ConfigureApplicationCookie(options =>
{
options.Cookie.Name = "CourseApp.Auth";
options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Account/AccessDenied";
options.LogoutPath = "/Account/Logout";
options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
options.SlidingExpiration = true;
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.SameSite = SameSiteMode.Lax;
});
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();The order of UseAuthentication and UseAuthorization matters. Authentication must establish the current user before authorization evaluates access rules. These middleware calls should appear before the endpoints are mapped.
UseHttpsRedirection also works together with secure cookie settings. If CookieSecurePolicy.Always is enabled, the application must be accessed through HTTPS. If local development is configured for HTTP only, the cookie may appear not to work. The safer solution is to correct the development HTTPS setup rather than weaken the cookie policy.
Important Cookie Options
| Option | Purpose |
|---|---|
Cookie.Name | Defines the cookie name visible in the browser. Use an application-specific name. |
LoginPath | Defines where unauthenticated users are sent when a challenge occurs. |
AccessDeniedPath | Defines where authenticated but unauthorized users are sent. |
ExpireTimeSpan | Controls the lifetime of the authentication ticket. |
SlidingExpiration | Allows the ticket lifetime to be renewed for active users under the configured rules. |
HttpOnly | Prevents client-side JavaScript from reading the cookie. |
SecurePolicy | Controls whether the cookie is sent only over HTTPS. |
SameSite | Restricts how the cookie is sent in cross-site contexts. |
Creating the Cookie during Login
With Identity, user credentials should be verified through UserManager or SignInManager. When PasswordSignInAsync succeeds, Identity creates the application cookie and adds it to the response.
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
public class AccountController : Controller
{
private readonly SignInManager<ApplicationUser> _signInManager;
public AccountController(SignInManager<ApplicationUser> signInManager)
{
_signInManager = signInManager;
}
[HttpGet]
[AllowAnonymous]
public IActionResult Login(string? returnUrl = null)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(
LoginViewModel model,
string? returnUrl = null)
{
if (!ModelState.IsValid)
return View(model);
var result = await _signInManager.PasswordSignInAsync(
model.Email,
model.Password,
model.RememberMe,
lockoutOnFailure: true);
if (result.Succeeded)
{
if (!string.IsNullOrWhiteSpace(returnUrl) &&
Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Dashboard");
}
if (result.IsLockedOut)
{
ModelState.AddModelError("", "The account is temporarily locked.");
}
else
{
ModelState.AddModelError("", "Invalid login details.");
}
return View(model);
}
}The RememberMe value controls persistent-session behavior. When selected, the user may remain signed in after closing the browser. Persistent login should not be the default choice on shared computers, kiosk devices or untrusted browsers.
Always validate a returnUrl with Url.IsLocalUrl. Redirecting to an unchecked external URL after login can create an open redirect vulnerability. Do not accept arbitrary external domains as post-login destinations.
Protecting MVC Pages
A dashboard controller can be protected with the [Authorize] attribute.
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[Authorize]
public class DashboardController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Profile()
{
return View();
}
}
[AllowAnonymous]
public class PublicController : Controller
{
public IActionResult About()
{
return View();
}
}When an unauthenticated request reaches /Dashboard/Index, the cookie handler can redirect it to the configured LoginPath. The original destination is commonly preserved in a returnUrl query-string parameter. After a successful login, the user can be returned to a safe local URL.
Role- and policy-based protection use the same authorization pipeline:
[Authorize(Roles = "Admin")]
public class AdministrationController : Controller
{
public IActionResult Index()
{
return View();
}
}
[Authorize(Policy = "CanViewReports")]
public class ReportsController : Controller
{
public IActionResult Index()
{
return View();
}
}Authentication answers the question “Who is the user?” Authorization answers the question “Is this user allowed to access this resource?” A signed-in user therefore does not automatically have permission to open every MVC page.
Handling Access Denied
The AccessDeniedPath is used when the user is authenticated but does not satisfy a required role or policy. A simple action can be defined as follows:
[AllowAnonymous]
public IActionResult AccessDenied()
{
return View();
}The access denied page should explain that the account lacks permission instead of sending the user back to the login page. The user is already authenticated, so another login prompt is confusing and does not solve the authorization problem.
Implementing Secure Sign-Out
Sign-out should invalidate the authentication cookie and remove it from the browser.
[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
return RedirectToAction("Index", "Home");
}Defining logout as a POST action and requiring antiforgery validation reduces the chance that another site can trigger a state-changing logout request unexpectedly. The user interface should submit an antiforgery-protected POST request rather than using a simple GET link for logout.
After sign-out, a request to a protected page should cause a new login challenge. If the application stores additional session-like data on the server, that data must also be cleared when appropriate. Removing the cookie alone does not guarantee that user-specific sensitive data has disappeared from caches or other storage.
Separating MVC and API Behavior
Cookie Authentication provides browser-friendly redirects for MVC pages. REST APIs generally should return 401 Unauthorized or 403 Forbidden instead of redirecting an API client to an HTML login page. When an application contains both MVC and API endpoints, authentication schemes and cookie events should be designed for each client type.
For example, an API controller can explicitly select the bearer scheme so that a cookie identity is not accidentally used for the API request:
[ApiController]
[Route("api/reports")]
[Authorize(AuthenticationSchemes =
JwtBearerDefaults.AuthenticationScheme)]
public class ReportsApiController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok(new { Message = "Protected API response" });
}
}Although this lesson focuses on cookies, separating MVC and API authentication expectations is an important design decision. JWT Bearer Authentication will be implemented in detail in a later lesson.
Common Mistakes
- Incorrect middleware order: Placing
UseAuthorizationbeforeUseAuthenticationcan prevent the current user from being established correctly. - Protecting the login action: Login and registration actions need
[AllowAnonymous]. - Trusting every redirect: Redirecting to an unchecked
returnUrlcan create an open redirect vulnerability. - Testing without HTTPS: A secure cookie will not be sent over ordinary HTTP when the policy requires HTTPS.
- Making persistent sessions the default: Persistent cookies create privacy and account-security risks on shared devices.
- Using GET for logout: Prefer POST and antiforgery protection for state-changing operations.
- Redirecting APIs to HTML login pages: API clients generally expect meaningful HTTP status codes such as 401 and 403.
- Storing sensitive data in the cookie: Keep authentication tickets small and avoid placing secrets or large private data in claims.
Practice Exercise
- Change the application cookie name in your Identity project to
CourseApp.Auth. - Connect
LoginPathandAccessDeniedPathto your AccountController actions. - Create a
DashboardControllerprotected with[Authorize]. - Open the dashboard while signed out and inspect the resulting redirect.
- Test the
returnUrlflow after login and verify that an external URL is rejected. - Add an action restricted to the Admin role and observe the access denied result with a normal user.
- Test POST-based logout with antiforgery validation enabled.
- Use browser developer tools to inspect the cookie's
HttpOnly,SecureandSameSiteattributes.
Conclusion
In this lesson, we protected ASP.NET Core MVC pages with Cookie Authentication, customized the application cookie created by Identity and implemented a safer sign-out flow. Login and access-denied paths, expiration, sliding expiration and cookie security options should be evaluated together to achieve an appropriate balance between usability and security.
Next, we will connect this cookie foundation to more detailed authorization rules based on roles, claims and policies. This will allow us to protect not only signed-in users, but also specific operations that should be available only to users with the appropriate permissions.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/mvc/security/authorization/simple?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.cookies.cookieauthenticationevents?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.cookies.cookieauthenticationdefaults?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/breaking-changes/10/cookie-authentication-api-endpoints?view=aspnetcore-10.0