ASP.NET Core MVC Interview Question #125

What are best practices for authentication, authorization, security, and state management in MVC?

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

Quick Interview Answer

Use a proven authentication system such as ASP.NET Core Identity or correctly configured authentication handlers rather than building password and session security from scratch. Enforce authorization on controllers/actions or through policies, and use resource-based authorization when access depends on the specific record.

Detailed Explanation

Use a proven authentication system such as ASP.NET Core Identity or correctly configured authentication handlers rather than building password and session security from scratch. Enforce authorization on controllers/actions or through policies, and use resource-based authorization when access depends on the specific record.

Protect browser state-changing requests against CSRF, preserve Razor's output encoding, validate local redirects, use HTTPS, secure cookies, and never trust client-submitted security-sensitive values. Keep session data small and purposeful, use TempData for short redirect messages, and manage Data Protection keys correctly in production. Security decisions must be enforced on the server even when the UI also hides unavailable operations.

Code Example

[Authorize(Policy = "CanManageProducts")]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Update(
    ProductEditViewModel model,
    CancellationToken cancellationToken)
{
    if (!ModelState.IsValid)
        return View(model);

    await _service.UpdateAsync(model, cancellationToken);
    TempData["Success"] = "Product updated.";
    return RedirectToAction(nameof(Index));
}