Skip to content
Tutorials Center
My learning

Topics

Lesson 139 of 182 ยท ASP.NET Core

Authentication and Authorization

Understand authentication vs authorization in ASP.NET Core - claims, schemes, cookies vs JWT bearer tokens, policies, roles, 401 vs 403 and safe password hashing, with runnable C# demos.

Two questions decide who may do what in a web application. First: who are you? That is authentication (authn). Second: are you allowed to do this? That is authorization (authz). They are separate steps with separate failure codes, and mixing them up is one of the most common sources of both confusing code and real security holes.

ASP.NET Core splits them cleanly. Authentication reads something the client sends (a cookie, a bearer token, an API key) and turns it into a ClaimsPrincipal, an object describing the user. Authorization then looks at that principal and the rules attached to an endpoint and decides to allow it or not. In this lesson you will learn the building blocks (claims, identities, schemes), compare cookies with JWT bearer tokens, protect endpoints with [Authorize]-style rules and policies, understand 401 versus 403, and hash passwords the way professionals do. You should be comfortable with middleware and dependency injection.

This lesson explains mechanics so you can reason about security. It is not a substitute for a vetted identity solution. In real products use ASP.NET Core Identity, or an external identity provider (OpenID Connect), instead of writing your own login system. Never invent your own cryptography.

Claims, identities and principals

Everything in .NET security is built from three types in System.Security.Claims:

  • A claim is one statement about a user: a name/value pair such as name = Ada, role = admin or permission = reports.read.
  • A ClaimsIdentity is a set of claims that came from one source, plus the authentication type (for example "cookie"). An identity is authenticated when its authentication type is not empty.
  • A ClaimsPrincipal holds one or more identities. In a web request it is exposed as HttpContext.User.
C# Building a ClaimsPrincipal by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice that one user has two Role claims; claims are a list, not a dictionary. And an unauthenticated request does not have User == null: it has an empty, unauthenticated principal, so context.User.Identity?.IsAuthenticated is false. Roles are just claims with a special type that IsInRole and [Authorize(Roles = ...)] look at.

Authentication schemes: cookies, JWT and friends

A scheme is a named way of authenticating, implemented by an authentication handler. Handlers do three jobs: authenticate (read credentials from the request and build a principal), challenge (what to do when an anonymous user hits a protected endpoint: redirect to a login page, or answer 401) and forbid (what to do when a known user lacks permission: show "access denied" or answer 403).

The two schemes you will meet most:

Cookie authentication JWT bearer authentication
Where the proof lives An encrypted cookie the browser sends automatically An Authorization: Bearer <token> header your code attaches
Typical client Server-rendered sites (Razor Pages, MVC), same-site apps Single-page apps, mobile apps, service-to-service APIs
State The cookie holds an encrypted ticket; sessions can be revoked server-side The token is self-contained and valid until it expires
Main risk CSRF (browser sends cookies for you) Theft of the token (anyone holding it is you); hard to revoke
Challenge result Redirect to a login page 401 with WWW-Authenticate: Bearer

Neither is "better". A browser app talking to its own backend is usually best served by cookies (HttpOnly, Secure, SameSite), which the browser protects from JavaScript. APIs called by other programs use bearer tokens, usually issued by a dedicated identity provider.

What is inside a JWT?

A JSON Web Token is three Base64URL parts joined by dots: header.payload.signature. The header says how it is signed, the payload holds claims (sub, exp, iss, aud, plus your own), and the signature is a hash-based proof (HMAC with a shared secret, or an RSA/ECDSA signature) over the first two parts. The payload is encoded, not encrypted: anyone can read it. The signature only guarantees it was not changed.

The real validation code lives in the NuGet package Microsoft.AspNetCore.Authentication.JwtBearer, which our runner does not have (it is not part of the shared framework). Here is how you would set it up in a project:

C#
// Read-only: needs the NuGet package Microsoft.AspNetCore.Authentication.JwtBearer
builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = "https://login.example.com";   // issuer that publishes signing keys
        options.Audience = "orders-api";
        // or, for a simple self-issued HS256 token:
        // options.TokenValidationParameters = new TokenValidationParameters
        // {
        //     ValidIssuer = "...", ValidAudience = "...",
        //     IssuerSigningKey = new SymmetricSecurityKey(keyBytes),
        //     ClockSkew = TimeSpan.FromMinutes(1)
        // };
    });

To see the idea without the package, the next demo builds and verifies an HS256 token with only the base class library. It is for learning: in production always use a maintained library, because token validation has many details (algorithm confusion, expiry, audience, key rotation).

C# Anatomy of a JWT (HS256, hand-built)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Read the payload line: it is plain JSON anyone can decode, so never put secrets in a JWT. The forged token has a valid structure but the signature no longer matches the modified payload, so verification fails, and so does a verifier with a different key. The constant-time comparison (FixedTimeEquals) avoids leaking how many leading bytes matched through timing. A real validator additionally checks exp, nbf, the issuer, the audience and that the alg header is the one you expect.

Protecting endpoints: authentication handler plus authorization

Now let us see the whole flow in a running app. ASP.NET Core lets you write your own scheme by deriving from AuthenticationHandler<TOptions>. The handler below reads Authorization: Bearer <token> and looks the token up in a small in-memory table (a stand-in for validating a JWT or calling an identity provider). Then we protect endpoints in three ways: simply requiring a signed-in user, requiring a policy, and requiring a role.

C# Custom scheme, policies, 401 versus 403

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Study the status codes, because they are the heart of the lesson:

  • /public needs nothing, so everyone gets 200.
  • An anonymous request to a protected endpoint gets 401 Unauthorized. Despite the name, this means "unauthenticated": the server does not know who you are. The handler's challenge sends it.
  • A known user who fails a rule gets 403 Forbidden: "I know who you are, and the answer is no." The handler's forbid sends it. Bob is authenticated but has no reports.read permission and no admin role, so he gets 403 on those endpoints.
  • A request with a bad token (AuthenticateResult.Fail) is treated as unauthenticated and challenged with 401.

Three kinds of rule appeared. RequireAuthorization() with no argument means "any authenticated user". RequireClaim and RequireRole are built-in requirements. RequireAssertion accepts a lambda for one-off logic: here the user must have five or more years of service.

[Authorize] in controllers and minimal APIs

Minimal APIs use .RequireAuthorization(...) on an endpoint or a route group; controllers and Razor Pages use the attribute form. They are the same system:

C#
// Read-only: attribute form in a controller
[Authorize]                                  // every action needs a signed-in user
public class OrdersController : ControllerBase
{
    [HttpGet]
    public IActionResult List() => Ok();

    [AllowAnonymous]                         // opt this action out
    [HttpGet("public-info")]
    public IActionResult Info() => Ok();

    [Authorize(Policy = "CanReadReports")]   // a named policy
    [HttpGet("report")]
    public IActionResult Report() => Ok();

    [Authorize(Roles = "admin,support")]     // admin OR support
    [HttpDelete("{id}")]
    public IActionResult Delete(int id) => NoContent();
}

You can also set a fallback policy that requires authentication on every endpoint unless it opts out with AllowAnonymous. That "secure by default" posture means a forgotten attribute fails closed instead of open:

C#
builder.Services.AddAuthorizationBuilder()
    .SetFallbackPolicy(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build());

Policies, requirements and resource-based checks

A policy is a named list of requirements. Each requirement is checked by one or more AuthorizationHandlers. Built-in requirements cover claims and roles; for anything else write your own. A typical custom rule is "the user may edit a document only if they own it", which depends on the document, not just the user. That is resource-based authorization: you call IAuthorizationService.AuthorizeAsync(user, resource, requirement) inside the handler or service, after loading the resource.

C# A custom requirement and resource-based check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Handler semantics are worth remembering: a requirement passes if at least one handler calls Succeed, and fails if none does. A handler that does not succeed simply abstains. Call context.Fail() only when you want to veto the requirement no matter what other handlers say. This example also runs without a web server at all, because authorization is plain DI services that you can unit test.

Passwords: hash, never store

If you do keep users' passwords, you store a hash, never the password and never an encrypted copy. A good password hash has three properties:

  1. It is one-way: you can verify a guess, but not recover the password.
  2. It uses a unique random salt per password, so two users with the same password get different hashes and precomputed tables are useless.
  3. It is deliberately slow (many iterations, or memory-hard), so guessing billions of passwords per second is not feasible. General-purpose hashes like SHA-256 or MD5 are far too fast for this.

The base class library provides PBKDF2 through Rfc2898DeriveBytes.Pbkdf2. ASP.NET Core Identity's PasswordHasher<TUser> wraps the same idea with a versioned format; use it (or Argon2 from a maintained package) in real systems.

C# Salted PBKDF2 password hashing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Two hashes of the same password differ because of the random salt. The stored string carries the version, the iteration count and the salt, so you can raise the iterations later and re-hash a user's password at their next login. Also note: never log passwords, never put them in URLs, and always send credentials over HTTPS. Add login rate limiting and (ideally) multi-factor authentication on top.

With cookie authentication, signing in means calling HttpContext.SignInAsync(scheme, principal). ASP.NET Core serializes the principal into an encrypted, signed cookie using the Data Protection system, and every later request that carries the cookie is authenticated automatically. Signing out deletes it. Our runner can do the whole round trip over loopback with a CookieContainer:

C# Sign in with a cookie

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first request is rejected, the login sets the cookie, and the HttpClient returns it on the next call, which succeeds. After sign-out the browser-side cookie is cleared and the endpoint is protected again. (Passing a password in the query string is only to keep the demo short: real login forms use a POST body, and credentials never go in URLs.)

Because browsers attach cookies automatically, cookie-based apps must defend against CSRF (cross-site request forgery): use SameSite cookies and ASP.NET Core's antiforgery tokens for forms. Bearer-token APIs are not vulnerable to CSRF in the same way, since the browser does not add the header on its own, but they carry the token-theft and revocation problems from the table above.

Security habits that matter

  • Fail closed. Use a fallback policy so endpoints require authentication unless marked AllowAnonymous.
  • Check on the server, always. Hiding a button in the UI is convenience, not security.
  • Order the middleware correctly: UseAuthentication() before UseAuthorization(), both before the endpoints, and after routing (see Middleware).
  • Keep tokens short-lived and use refresh tokens or re-authentication; keep secrets and signing keys out of source code (see Configuration and Options).
  • Use HTTPS everywhere, HttpOnly/Secure cookies and HSTS.
  • Do not leak which half failed. A login form should say "invalid username or password", not "no such user".
  • Return the right code: 401 for unauthenticated, 403 for authenticated but not allowed (sometimes 404 on purpose to hide that a resource exists).
  • Authorize against the resource, not just the user type: "can this user edit this document?" prevents insecure direct object reference bugs, one of the most common API vulnerabilities.
  • Let experts do the hard parts: ASP.NET Core Identity, OpenID Connect providers, and maintained JWT libraries.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A signed-in user calls an endpoint that requires the admin role but does not have it. What status does ASP.NET Core return by default?

    The user is authenticated, so the failure is authorization: the forbid action runs and returns 403. 401 is for requests where the user is not authenticated.
  2. 2. What is true about the payload of a JWT?

    A JWT is signed, not encrypted. Decoding the payload needs no key, so it must never contain secrets.
  3. 3. Why does a password hash use a unique random salt per password?

    A salt makes every hash unique and defeats rainbow tables and cross-user comparison. Hashing is one-way; you verify by hashing the guess with the stored salt.
  4. 4. Where should app.UseAuthentication() be placed relative to app.UseAuthorization()?

    Authentication builds HttpContext.User; authorization then evaluates policies against it. Reversing them makes every request look anonymous to the authorization step.
  5. 5. Which approach best fits a rule like 'users may edit only their own documents'?

    The decision depends on the specific resource, so call IAuthorizationService with the loaded resource and a handler that compares the owner.

Summary

  • Authentication establishes identity as a ClaimsPrincipal made of claims; authorization decides what that principal may do.
  • Schemes (cookie, JWT bearer, custom) are implemented by handlers that authenticate, challenge (401) and forbid (403).
  • Cookies suit server-rendered sites (use HttpOnly, Secure, SameSite and antiforgery); bearer tokens suit APIs and mobile apps. A JWT is signed, not encrypted.
  • Protect endpoints with RequireAuthorization or [Authorize], using roles, claims, policies and custom requirements; prefer a fallback policy so everything is protected by default.
  • Use resource-based authorization (IAuthorizationService) when the rule depends on the data being accessed.
  • Store only salted, slow password hashes (PBKDF2, Argon2, or ASP.NET Core Identity), compare in constant time, and never roll your own cryptography.

Next: REST API Design with ASP.NET Core