Authentication and authorisation are distinct concerns that frequently get conflated in enterprise ASP.NET Core MVC applications. Password-based authentication—even when wrapped in secure, HttpOnly, SameSite=Strict cookies—remains vulnerable to phishing, credential stuffing, and password reuse. Meanwhile, static [Authorize(Roles = "Admin")] checks break down when access depends on resource ownership, tenant boundaries, or dynamic business rules.
Modern ASP.NET Core addresses both sides of this security model: Passkeys (WebAuthn / FIDO2) replace shared secrets with asymmetric public-key cryptography bound to your origin domain, while Policy-Based Authorisation IAuthorizationHandler evaluates fine-grained requirements against users and domain resources. This guide covers how to wire WebAuthn passkey registration and sign-in into ASP.NET Core MVC, enforce resource-aware authorisation policies, and verify the pipeline end-to-end.
1. Architectural Blueprint & Security Boundaries
A clean security pipeline separates identity verification (who the user is) from permission evaluation (whether the user can perform a specific action on a target resource):
Security Layer | Core Mechanism | What It Solves |
Passkey Authentication (WebAuthn) | FIDO2 / WebAuthn + ASP.NET Core Identity / Cookie Sign-In | Eliminates passwords and shared secrets; resists phishing via origin-bound challenge-response signatures. |
Session Management | Encrypted Authentication Cookie | Maintains an authenticated ClaimsPrincipal across MVC requests once passkey assertion succeeds. |
Policy & Resource Authorisation | IAuthorizationRequirement + AuthorizationHandler<TReq, TRes>
| Enforces fine-grained rules (e.g., document ownership, approval limits, department scope) beyond coarse roles. |
Browser (WebAuthn API) ──1. Request Challenge──> [PasskeysController]
│ │
│<──2. Cryptographic Challenge + RP ID ─────────────┤
│ │
├──3. Biometric / Device Key Sign ───┐ │
│ ▼ │
└──4. Attestation / Assertion ──> [PasskeysController]
│
▼ (Verified)
SignInAsync (Cookie Scheme)
│
▼
[IAuthorizationService.AuthorizeAsync]
│
▼
[DocumentOwnerAuthorizationHandler] ──> Allow / Forbid
2. Domain Models & Resource Authorisation Contracts
Suppose users manage sensitive financial or operational documents, and only the document's owner—or an authorised compliance reviewer in the same department—may approve or edit a draft.
C#
using Microsoft.AspNetCore.Authorization;
public sealed record FinancialDocument(
Guid Id,
string Title,
string OwnerUserId,
string DepartmentCode,
decimal Amount,
bool IsApproved
);
public sealed record StoredPasskeyCredential(
byte[] CredentialId,
byte[] PublicKey,
uint SignatureCount,
string UserId,
string DisplayName
);
public sealed class DocumentEditRequirement : IAuthorizationRequirement
{
public decimal MaxUnreviewedAmount { get; }
public DocumentEditRequirement(decimal maxUnreviewedAmount)
{
MaxUnreviewedAmount = maxUnreviewedAmount;
}
}
3. Implementing a Resource-Based AuthorizationHandler
Rather than embedding if (doc.OwnerUserId != currentUserId) checks inside controller actions or views, encapsulate the rule inside an AuthorizationHandler<TRequirement, TResource> and register a named policy.
C#
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
public sealed class DocumentEditAuthorizationHandler
: AuthorizationHandler<DocumentEditRequirement, FinancialDocument>
{
private readonly ILogger<DocumentEditAuthorizationHandler> _logger;
public DocumentEditAuthorizationHandler(ILogger<DocumentEditAuthorizationHandler> logger)
{
_logger = logger;
}
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
DocumentEditRequirement requirement,
FinancialDocument resource)
{
var userId = context.User.FindFirstValue(ClaimTypes.NameIdentifier);
var userDept = context.User.FindFirstValue("dept_code");
if (string.IsNullOrWhiteSpace(userId))
{
return Task.CompletedTask;
}
if (resource.IsApproved)
{
_logger.LogWarning(
"User {UserId} attempted to modify already-approved document {DocumentId}.",
userId,
resource.Id);
return Task.CompletedTask;
}
bool isOwner = string.Equals(resource.OwnerUserId, userId, StringComparison.Ordinal);
bool isSameDeptReviewer =
context.User.IsInRole("ComplianceReviewer") &&
string.Equals(resource.DepartmentCode, userDept, StringComparison.OrdinalIgnoreCase) &&
resource.Amount <= requirement.MaxUnreviewedAmount;
if (isOwner || isSameDeptReviewer)
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
4. WebAuthn Passkey Challenge & Assertion Flow
Passkey authentication follows a strict challenge-response flow:
The server generates a cryptographically random challenge, stores it server-side tied to the session or user identifier with a short expiration, and sends WebAuthn options (PublicKeyCredentialCreationOptions for registration or PublicKeyCredentialRequestOptions for login).
The browser's WebAuthn API prompts the user's authenticator (Windows Hello, Touch ID, Face ID, or hardware security key) and returns a signed assertion or attestation.
The server verifies the challenge, relying party (rpId), expected origin, cryptographic signature, and counter before signing the user into the MVC cookie authentication scheme.
Below is an abstraction over a WebAuthn verification service (such as Fido2NetLib or your organization's WebAuthn verifier) paired with an MVC controller that issues a standard authentication cookie after cryptographic verification succeeds:
C#
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
public interface IWebAuthnChallengeService
{
Task<object> CreateRegistrationOptionsAsync(string userId, string userName, CancellationToken ct);
Task<StoredPasskeyCredential> VerifyRegistrationAsync(string userId, string attestationJson, CancellationToken ct);
Task<object> CreateAssertionOptionsAsync(string? userName, CancellationToken ct);
Task<(string UserId, string UserName, uint NewSignCount)> VerifyAssertionAsync(string assertionJson, CancellationToken ct);
}
public interface IPasskeyCredentialStore
{
Task SaveCredentialAsync(StoredPasskeyCredential credential, CancellationToken ct);
Task UpdateSignCountAsync(byte[] credentialId, uint newSignCount, CancellationToken ct);
}
[ApiController]
[Route("auth/passkeys")]
public sealed class PasskeysController : ControllerBase
{
private readonly IWebAuthnChallengeService _webAuthnService;
private readonly IPasskeyCredentialStore _credentialStore;
private readonly ILogger<PasskeysController> _logger;
public PasskeysController(
IWebAuthnChallengeService webAuthnService,
IPasskeyCredentialStore credentialStore,
ILogger<PasskeysController> logger)
{
_webAuthnService = webAuthnService;
_credentialStore = credentialStore;
_logger = logger;
}
[Authorize]
[HttpPost("register/options")]
public async Task<IActionResult> GetRegistrationOptions(CancellationToken cancellationToken)
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
var userName = User.Identity?.Name;
if (string.IsNullOrWhiteSpace(userId) || string.IsNullOrWhiteSpace(userName))
{
return Unauthorized();
}
var options = await _webAuthnService.CreateRegistrationOptionsAsync(userId, userName, cancellationToken);
return Ok(options);
}
[Authorize]
[HttpPost("register/complete")]
public async Task<IActionResult> CompleteRegistration([FromBody] string attestationJson, CancellationToken cancellationToken)
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (string.IsNullOrWhiteSpace(userId))
{
return Unauthorized();
}
try
{
var credential = await _webAuthnService.VerifyRegistrationAsync(userId, attestationJson, cancellationToken);
await _credentialStore.SaveCredentialAsync(credential, cancellationToken);
_logger.LogInformation("Registered passkey credential for user {UserId}.", userId);
return Ok(new { Status = "PasskeyRegistered" });
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Passkey registration failed for user {UserId}.", userId);
return BadRequest(new { Error = "Unable to verify passkey attestation." });
}
}
[AllowAnonymous]
[HttpPost("login/options")]
public async Task<IActionResult> GetLoginOptions([FromQuery] string? userName, CancellationToken cancellationToken)
{
var options = await _webAuthnService.CreateAssertionOptionsAsync(userName, cancellationToken);
return Ok(options);
}
[AllowAnonymous]
[HttpPost("login/complete")]
public async Task<IActionResult> CompleteLogin([FromBody] string assertionJson, CancellationToken cancellationToken)
{
try
{
var (userId, userName, newSignCount) =
await _webAuthnService.VerifyAssertionAsync(assertionJson, cancellationToken);
await _credentialStore.UpdateSignCountAsync(
Convert.FromBase64String(userId), // Replace with credentialId byte[] from assertion result
newSignCount,
cancellationToken);
var claims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, userId),
new(ClaimTypes.Name, userName),
new("auth_method", "webauthn-passkey"),
new("dept_code", "FIN")
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
principal,
new AuthenticationProperties
{
IsPersistent = true,
AllowRefresh = true,
IssuedUtc = DateTimeOffset.UtcNow
});
_logger.LogInformation("User {UserId} authenticated via passkey.", userId);
return Ok(new { Status = "Authenticated" });
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Passkey assertion verification failed.");
return Unauthorized(new { Error = "Passkey authentication failed." });
}
}
}
5. Enforcing Policy Authorization in MVC Controllers and Razor Views
Once the user is authenticated via a passkey-backed cookie session, controllers inject IAuthorizationService to evaluate resource-specific policies imperatively.
C#
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
public interface IDocumentRepository
{
Task<FinancialDocument?> GetByIdAsync(Guid id, CancellationToken ct);
Task SaveAsync(FinancialDocument document, CancellationToken ct);
}
[Authorize]
[Route("documents")]
public sealed class DocumentsController : Controller
{
private readonly IDocumentRepository _repository;
private readonly IAuthorizationService _authorizationService;
public DocumentsController(
IDocumentRepository repository,
IAuthorizationService authorizationService)
{
_repository = repository;
_authorizationService = authorizationService;
}
[HttpPost("{id:guid}/edit")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Guid id, string newTitle, CancellationToken cancellationToken)
{
var document = await _repository.GetByIdAsync(id, cancellationToken);
if (document is null)
{
return NotFound();
}
var authResult = await _authorizationService.AuthorizeAsync(
User,
document,
policyName: "CanEditFinancialDocument");
if (!authResult.Succeeded)
{
// Returns 403 Forbid when authenticated, or challenges if unauthenticated
return Forbid();
}
var updated = document with { Title = newTitle };
await _repository.SaveAsync(updated, cancellationToken);
return RedirectToAction(nameof(Details), new { id });
}
[HttpGet("{id:guid}")]
public async Task<IActionResult> Details(Guid id, CancellationToken cancellationToken)
{
var document = await _repository.GetByIdAsync(id, cancellationToken);
if (document is null)
{
return NotFound();
}
return View(document);
}
}
In a Razor view (Views/Documents/Details.cshtml), you can inject IAuthorizationService directly so edit controls only render when the policy succeeds:
Razor CSHTML
@using Microsoft.AspNetCore.Authorization
@model FinancialDocument
@inject IAuthorizationService AuthorizationService
@{
var canEditResult = await AuthorizationService.AuthorizeAsync(User, Model, "CanEditFinancialDocument");
}
<h2>@Model.Title</h2>
<p>Amount: @Model.Amount.ToString("C")</p>
@if (canEditResult.Succeeded)
{
<form asp-action="Edit" asp-route-id="@Model.Id" method="post">
@Html.AntiForgeryToken()
<input type="text" name="newTitle" value="@Model.Title" class="form-control" />
<button type="submit" class="btn btn-primary mt-2">Save Changes</button>
</form>
}
6. Bootstrapping Authentication and Authorization (Program.cs)
Register the cookie authentication scheme, antiforgery protection, and the custom resource policy during application startup:
C#
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "__Host-EnterpriseAuth";
options.Cookie.HttpOnly = true;
options.Cookie.SameSite = SameSiteMode.Strict;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.LoginPath = "/auth/login";
options.AccessDeniedPath = "/auth/denied";
options.ExpireTimeSpan = TimeSpan.FromHours(8);
options.SlidingExpiration = true;
});
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("CanEditFinancialDocument", policy =>
{
policy.RequireAuthenticatedUser();
policy.Requirements.Add(new DocumentEditRequirement(maxUnreviewedAmount: 25_000m));
});
});
builder.Services.AddScoped<IAuthorizationHandler, DocumentEditAuthorizationHandler>();
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
7. Conclusion
Pairing WebAuthn Passkeys for phishing-resistant authentication with Policy-Based Authorization (IAuthorizationHandler) for fine-grained resource access creates a defense-in-depth security model in ASP.NET Core MVC. Passkeys eliminate password-based attack surfaces while preserving familiar cookie session handling for MVC views and controllers, and custom authorization handlers keep ownership and business rules centralized, explicit, and testable across both actions and Razor templates.
Join the conversation! Your thoughts help the community grow.