Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 52 ยท Projects

Project: Notes API with Authentication

Build a Notes API in ASP.NET Core with API key authentication, a fallback policy, role policies and per-user resource authorization that stops IDOR bugs.

Most real APIs are not public. They know who is calling, and they decide what that caller may do. In this project you build a notes service where every request must carry an API key, every note belongs to one user, users can only touch their own notes, and an administrator has a few extra powers. It exercises the whole security chain of ASP.NET Core: an authentication handler, a fallback authorization policy, a role policy and a resource-based authorization handler.

You will learn it in two steps. First the authentication handler on its own, so you see exactly what turns a header into an identity. Then the complete API with authorization on top. Everything runs live: the program starts Kestrel on loopback and calls itself with HttpClient.

Authentication, authorization and where each decision lives

Two questions are asked of every request, in this order:

  1. Authentication: who are you? The authentication handler reads credentials (here an X-Api-Key header) and builds a ClaimsPrincipal, or fails.
  2. Authorization: may you do this? Policies check the principal's claims against the endpoint, and handlers can also check the principal against a specific object, such as one note.
flowchart TD
    R["Request with X-Api-Key"] --> A["UseAuthentication<br/>ApiKeyHandler builds the user"]
    A --> Z{"UseAuthorization<br/>endpoint policy ok?"}
    Z -->|"no user"| U["401 Unauthorized"]
    Z -->|"wrong role"| F["403 Forbidden"]
    Z -->|"yes"| H["Endpoint handler<br/>loads the note"]
    H --> O{"Resource check<br/>is this user's note?"}
    O -->|"no"| N["404 Not Found"]
    O -->|"yes"| OK["200 / 204"]

The middleware decides who you are and enforces endpoint policies; the handler then checks the specific note.

The difference between 401 and 403 matters: 401 Unauthorized really means "unauthenticated" (we do not know who you are), while 403 Forbidden means "we know who you are, and the answer is no". The concepts are covered in Authentication Concepts and Authorization: Roles, Policies and Handlers; this project applies them.

Step 1: an API key authentication handler

An authentication handler derives from AuthenticationHandler<TOptions> and overrides HandleAuthenticateAsync. Its three possible results are:

  • NoResult(): the request carries no credentials for this scheme (anonymous),
  • Fail(message): credentials were present but wrong,
  • Success(ticket): a valid identity.

Never store API keys in plain text. Like passwords, keys are kept as hashes: the user directory stores the SHA-256 of each key, and the handler hashes the presented key and looks the hash up. If the directory leaks, attackers get hashes they cannot use as keys. (API keys are long random secrets, so a fast hash such as SHA-256 is acceptable here; low-entropy passwords need a slow password hash instead.) Looking up by hash also avoids comparing secrets character by character, which can leak timing information.

C# Step 1: the API key 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.

Four things to notice in the output:

  • /open works with no key because of AllowAnonymous().
  • /me with no key is 401: the handler returned NoResult, the principal is anonymous, and RequireAuthorization() demands an authenticated user.
  • /me with a wrong key is also 401: the handler returned Fail, so the challenge runs.
  • With a valid key the endpoint receives a populated ClaimsPrincipal (bound directly as a handler parameter) with id, name and roles. Alice has the role user; Root has both user and admin.

A custom handler like this suits internal and machine-to-machine APIs. For end users, prefer standard mechanisms: cookies for browser apps and JWT bearer tokens or OAuth for APIs (Cookie and JWT Bearer Authentication). The authorization half of this project works identically with any of them, because it only reads claims.

Step 2: authorization

Three layers of authorization protect the notes API.

A fallback policy. FallbackPolicy applies to every endpoint that has no authorization metadata of its own. Setting it to "authenticated user required" flips the API to secure by default: a forgotten RequireAuthorization() can no longer expose an endpoint. Public endpoints must opt out with AllowAnonymous().

A role policy. AddPolicy("AdminOnly", p => p.RequireRole("admin")) protects the administrative endpoint. A signed-in non-admin gets 403.

Resource-based authorization. Roles and policies cannot answer "does this note belong to this user?", because the answer depends on data. For that you inject IAuthorizationService and call AuthorizeAsync(user, note, requirement). A handler written for the requirement then compares note.OwnerId with the user's id. Our handler allows owners to do anything with their notes, and lets admins read any note but not change it.

There is one more design decision: when Bob asks for Alice's note, we answer 404, not 403. A 403 confirms the note exists, and attackers can enumerate ids. Answering exactly as if the note did not exist leaks nothing. Skipping this check altogether is the classic IDOR bug (insecure direct object reference, called broken object level authorization in the OWASP API Top 10), and it is the most common serious API vulnerability.

Here is the complete API. The client at the end plays Alice, Bob, Root and an anonymous caller.

C# The Notes API with authorization

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.

Go through the transcript:

  • Fallback policy. /health is open; /notes returns 401 both without a key and with a bad key, although the endpoint has no RequireAuthorization() call. That is the fallback at work.
  • Ownership by construction. POST /notes takes the owner from the authenticated claims, never from the request body. A client cannot create a note "as" someone else, because there is no field to lie in. The same goes for the list: ForOwner(user.UserId()) can only return the caller's notes.
  • Object-level checks. Bob's GET, PUT and DELETE on Alice's note all return 404, exactly like a note that never existed (/notes/404). Alice reads it fine.
  • Roles and operations. Root reads Bob's note (Read allows admins) but the PUT gets 404 (denied, and hidden like any other foreign note), since the handler only grants admins the read operation. Root passes AdminOnly; Alice gets 403 (authenticated but wrong role); the anonymous caller gets 401.

Notice that the checks are positive: the handler only calls Succeed for allowed cases, and everything else is denied by default. Writing authorization as "deny unless a rule says yes" is far safer than "allow unless a rule says no".

Hardening and extending the project

  • Transport. API keys travel in a header; always use HTTPS in production (see Web Security Essentials). Never accept keys in query strings, which end up in logs and browser history.
  • Key management. Issue long random keys (at least 32 bytes from RandomNumberGenerator), show them to the user only once, store the hash, allow revocation and rotation, and add a key prefix (such as nk_live_) so leaked keys are easy to scan for.
  • Rate limiting. Partition limits by user id instead of IP address so that one noisy client cannot starve others (Rate Limiting, Health Checks and Resilience of the App).
  • Persistence. Replace the in-memory store with a database; add WHERE OwnerId = @user to every query as a second line of defense.
  • Auditing. Log who did what to which note, with the user id and trace id (Observability in Production).
  • Tests. The transcript above is the start of an integration test suite: assert each status code (Testing ASP.NET Core Apps).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between 401 and 403?

    401 Unauthorized actually means unauthenticated. 403 Forbidden means the identity is known but lacks permission.
  2. 2. What does setting FallbackPolicy to RequireAuthenticatedUser achieve?

    The fallback applies when no [Authorize] or AllowAnonymous metadata exists. Public endpoints must opt out explicitly.
  3. 3. Why does the API return 404 when Bob requests Alice's note?

    Answering exactly as if the note did not exist avoids leaking which ids are valid.
  4. 4. Why take the note owner from the authenticated claims instead of from the JSON body?

    Identity must come from the authentication result, never from data the client controls.
  5. 5. Where should an API key be stored on the server?

    Only a hash is stored. The handler hashes the presented key and looks that up.

Summary

  • Authentication builds the ClaimsPrincipal (a handler returns NoResult, Fail or Success); authorization decides what that principal may do.
  • 401 means unauthenticated, 403 means authenticated but not permitted.
  • A fallback policy makes the API secure by default; use AllowAnonymous for the few public endpoints and RequireAuthorization("Policy") for role-specific ones.
  • Resource-based authorization (IAuthorizationService plus an AuthorizationHandler<TRequirement, TResource>) enforces ownership and prevents IDOR bugs; answer 404 to hide other users' objects.
  • Take identity from claims, never from the request body, store key hashes, and deny unless a rule explicitly allows.

Next: Project: Real-time Chat with SSE and WebSockets