.NET › Authentication & Authorization (Identity, JWT, OAuth)

How do authentication and authorization work together in a .NET application, and how would you implement both role-based and policy-based access control?

Advanced

Answer

Authentication verifies who a user is (commonly via JWT bearer tokens, OAuth/OpenID Connect, or cookies), while authorization determines what an already-authenticated user is permitted to do -- in practice: a user authenticates and receives a token, that token is validated on each subsequent request, and only then does the authorization system check the user's roles or custom policy conditions before granting access to a specific resource. Role-based authorization restricts access using the [Authorize(Roles = "...")] attribute; policy-based authorization defines more flexible, custom rules (like requiring a specific claim value) that can express conditions roles alone can't capture.
// Configuring JWT bearer authentication
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options => {
        options.Authority = "https://your-identity-provider.com";
        options.Audience = "your-api";
    });

// Role-based authorization
[Authorize(Roles = "Admin")]
public IActionResult SecureEndpoint() => Ok("Only admins can access this.");

// Policy-based authorization for more granular rules
services.AddAuthorization(options =>
    options.AddPolicy("MustBeOver18", policy => policy.RequireClaim("Age", "18+")));
Real-world example An internal admin panel restricts an entire controller to the Admin role via [Authorize(Roles = "Admin")], while a separate age-restricted content endpoint uses a custom "MustBeOver18" policy checking a specific claim, since that particular rule doesn't map cleanly onto a simple role.

Common follow-ups: What happens if a request fails authorization but authentication succeeded -- what status code is returned, and why?;How would you combine multiple policies or require several claims simultaneously for one endpoint?