Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 52 ยท Authentication and Authorization

Authentication Concepts

Understand ASP.NET Core authentication: schemes, handlers, claims and ClaimsPrincipal, challenge versus forbid, and build a custom API key handler.

Almost every real application has to answer two questions about each request: who is calling? and are they allowed to do this? The first question is authentication, the second is authorization. ASP.NET Core keeps them strictly separate, and understanding that separation makes the rest of the security features (cookies, JWT, Identity, policies) much easier to learn.

In this lesson you will meet the building blocks: claims, identities and the ClaimsPrincipal; authentication schemes and handlers; and the difference between a challenge and a forbid response. At the end you will write a complete custom handler that authenticates callers with an API key. If you want a refresher on records, classes and interfaces first, see the C# tutorial.

Claims, identities and principals

ASP.NET Core does not have a "user" class. A signed-in caller is described by a ClaimsPrincipal from System.Security.Claims, and it is built from three layers:

  • A claim is one statement about the caller: a type and a string value, such as name = Ada or role = admin.
  • A ClaimsIdentity is a set of claims that came from one source, plus an authentication type (such as Cookies or ApiKey). An identity is authenticated only if it has an authentication type.
  • A ClaimsPrincipal holds one or more identities. This is what HttpContext.User returns.
flowchart LR
    P["ClaimsPrincipal<br/>(HttpContext.User)"] --> I1["ClaimsIdentity<br/>type: ApiKey"]
    I1 --> C1["name = Ada"]
    I1 --> C2["role = admin"]
    I1 --> C3["plan = pro"]

A principal contains identities; each identity contains claims.

Claims are just data, so you can experiment with them without a web server.

C# Building and reading a ClaimsPrincipal

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 two details. A person can have several claims of the same type (two roles), and IsInRole simply looks for a claim of the role type with that value. And an anonymous request is not null: HttpContext.User is always an object, just one whose identity is not authenticated. So check User.Identity?.IsAuthenticated, never User == null.

Claim values are strings. Keep them small and stable (an id, a role, a tenant), because with cookie and token authentication they are copied into every request.

Schemes and handlers

A scheme is a named way of authenticating. It pairs a name ("Cookies", "Bearer", "ApiKey") with a handler, a class that knows how to do the work for that scheme. A handler can do up to three things:

Operation When it runs What it does
Authenticate Every request that reaches the authentication middleware Reads the credentials (cookie, header, token) and produces a ClaimsPrincipal, or reports no result or failure
Challenge When an anonymous caller hits something that needs a login Tells the caller to authenticate: redirect to a login page, or answer 401 with a WWW-Authenticate header
Forbid When a signed-in caller lacks permission Answers "you are known, but not allowed": 403 for APIs, a redirect to an "access denied" page for cookies

You register schemes with AddAuthentication, and one of them is the default scheme:

C#
builder.Services
    .AddAuthentication("ApiKey")                       // default scheme name
    .AddScheme<AuthenticationSchemeOptions, ApiKeyHandler>("ApiKey", options => { });

Then the pipeline needs two middlewares, in this order:

C#
app.UseAuthentication();   // runs the default handler's Authenticate, fills HttpContext.User
app.UseAuthorization();    // enforces [Authorize] / RequireAuthorization on the endpoint

UseAuthentication only identifies the caller; it never rejects a request on its own. Rejection is the job of authorization. If you forget UseAuthentication, every request looks anonymous even with valid credentials, a very common first-day bug. The Middleware Pipeline lesson explains why the order matters.

Challenge versus forbid

These two failures are easy to mix up and map to two different HTTP status codes.

flowchart TD
    R["Request reaches a protected endpoint"] --> A{"Authenticated?"}
    A -- "No" --> CH["Challenge<br/>401 Unauthorized"]
    A -- "Yes" --> P{"Allowed by the policy?"}
    P -- "No" --> FB["Forbid<br/>403 Forbidden"]
    P -- "Yes" --> OK["Run the endpoint"]

401 means "I do not know who you are"; 403 means "I know who you are, and the answer is no".

Despite its name, 401 Unauthorized is about authentication. Sending different credentials might fix it. 403 Forbidden is about authorization: the credentials were fine, and retrying with the same ones will never help. A good API returns the right one, because clients react differently (prompt for login versus show "no access").

Writing a custom handler: API keys

API keys are the simplest credential for machine-to-machine calls: the client sends a secret in a header, the server looks it up. ASP.NET Core has no built-in handler for them, which makes this a great exercise, because a custom handler touches every concept above.

A handler derives from AuthenticationHandler<TOptions> and overrides HandleAuthenticateAsync. It returns one of three results:

  • AuthenticateResult.NoResult(): no credentials were presented. The request stays anonymous, and other schemes (or anonymous endpoints) can still work.
  • AuthenticateResult.Fail(message): credentials were presented but are wrong.
  • AuthenticateResult.Success(ticket): the caller is identified. The ticket wraps the principal.
C# A custom API key authentication handler

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 six lines of output as a story:

  1. /public has no authorization requirement, so anyone gets in.
  2. /whoami without a key: the handler returned NoResult, the caller is anonymous, authorization demands a signed-in user, so the challenge runs and the client gets 401 with our WWW-Authenticate hint.
  3. A wrong key gives Fail. The result is also a challenge, so again 401.
  4. A valid key produces the principal, and the endpoint reads it through a plain ClaimsPrincipal parameter.
  5. Ada is authenticated but not an admin, so the policy fails and the forbid path answers 403. The base handler's default forbid is exactly that.
  6. The admin key passes both checks.

Never keep real API keys in source code or compare them with == in production. Store only hashes, look them up by hash, and compare secrets with CryptographicOperations.FixedTimeEquals so timing differences do not leak information. The dictionary above is a teaching device.

Overriding challenge and forbid

The base class already answers 401 for a challenge and 403 for a forbid. Cookie authentication overrides both to redirect instead, because browsers need a page to land on. An API handler overrides them only to add detail (like the WWW-Authenticate header above) or to write a JSON problem body. You can see each default in the next example, which asks the handler directly instead of going through an endpoint.

C# Calling the authentication service directly

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 three outcomes of AuthenticateAsync (none, failure, succeeded) are exactly what a handler returns, and the default challenge and forbid are plain 401 and 403.

Several schemes at once

An app can register more than one scheme: a cookie for the browser UI and a bearer token for its API, for example. Then you pick a scheme per endpoint (RequireAuthorization(new AuthorizeAttribute { AuthenticationSchemes = "ApiKey" })) or build a policy that names its schemes. When several schemes are active, an endpoint tries each listed scheme and uses the first successful principal. The next lesson, Cookie and JWT Bearer Authentication, builds on this by looking at the two most common real schemes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A request carries a valid login, but the endpoint requires the admin role and the user is not an admin. Which response is correct?

    Authentication succeeded, authorization failed. That is a forbid, which maps to 403. 401 is for callers that are not authenticated.
  2. 2. What does UseAuthentication() do in the pipeline?

    Authentication only identifies the caller. Rejecting anonymous or unauthorized callers is the job of UseAuthorization together with the endpoint's authorization metadata.
  3. 3. Which AuthenticateResult should a handler return when the request has no credentials at all?

    NoResult means "this scheme has nothing to say". The request stays anonymous, so public endpoints and other schemes keep working. Fail is for credentials that were presented but are invalid.
  4. 4. How can you tell whether a ClaimsIdentity represents a signed-in caller?

    IsAuthenticated is true only when the identity was created with an authentication type. HttpContext.User is never null; anonymous requests get an identity without one.

Summary

  • A ClaimsPrincipal holds identities, and identities hold claims; HttpContext.User is never null.
  • A scheme is a name plus a handler that can authenticate, challenge and forbid.
  • UseAuthentication identifies the caller; UseAuthorization decides whether the endpoint may run.
  • Challenge means 401 (not authenticated); forbid means 403 (authenticated but not allowed).
  • A custom handler derives from AuthenticationHandler<TOptions> and returns NoResult, Fail or Success.
  • Several schemes can coexist; endpoints choose which ones they accept.

Next: Cookie and JWT Bearer Authentication