📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the difference between authentication and authorisation? Explain how authentication works in ASP.NET Core: authentication schemes and handlers, ClaimsPrincipal and HttpContext.User, and why the order of UseAuthentication and UseAuthorization matters.

Authentication vs authorisation and the ASP.NET Core authentication model: schemes, handlers, ClaimsPrincipal, challenge vs forbid, and middleware order.

Beginner Theory Beginner aspnet-core authentication authorization claims middleware security

🎯 Key points

  • Authentication = who you are (401); authorisation = what you may do (403)
  • A scheme is a name plus a handler: cookies, JwtBearer, OpenIdConnect
  • Handler turns a credential into a ClaimsPrincipal on HttpContext.User; it never blocks the request
  • Order: UseRouting -> UseCors -> UseAuthentication -> UseAuthorization -> endpoints; misordering makes every caller anonymous or skips endpoint metadata
  • Challenge -> 401 or login redirect; Forbid -> 403; .NET 10 cookies return 401/403 for API endpoints
  • Default scheme via AddAuthentication(scheme); with several schemes, name them on policies
  • Fallback policy RequireAuthenticatedUser so a forgotten [Authorize] is not an anonymous endpoint

⏱ 30-second answer

Authentication answers who are you? and authorisation answers what are you allowed to do? In ASP.NET Core, authentication is built from schemes: a name plus an authentication handler (cookies, JwtBearer, OpenIdConnect, or your own). The handler reads a credential from the request, validates it and produces a ClaimsPrincipal, which the authentication middleware puts on HttpContext.User. The authorisation middleware then checks the endpoint's [Authorize] metadata against that principal: no identity means a challenge (401 or a login redirect), an identity without permission means forbid (403).

Order matters: UseAuthentication must run before UseAuthorization, and both after routing and CORS, or the user is anonymous when the decision is made. The trade-off is flexibility versus clarity: several schemes are powerful, but every extra scheme is another way to be authenticated by accident.

🗣 Full answer (senior)

How I would answer this in an interview

"Authentication is proving identity: the request carries a cookie, a bearer token or an API key, and the server works out who is calling. Authorisation comes after: given that identity, is this caller allowed to do this action on this resource? The HTTP status codes follow the same split: 401 means 'I don't know who you are', 403 means 'I know who you are, and the answer is no'.

In ASP.NET Core, authentication is organised around schemes. AddAuthentication().AddCookie().AddJwtBearer() registers named schemes, each backed by a handler. On every request, UseAuthentication asks the default scheme's handler to authenticate; if it succeeds, the handler returns an AuthenticationTicket holding a ClaimsPrincipal, and the middleware sets HttpContext.User. It never rejects a request by itself; an anonymous request just carries an empty principal. Then UseAuthorization looks at the endpoint chosen by routing, reads its [Authorize] or RequireAuthorization() metadata, evaluates the policy, and if it fails calls ChallengeAsync (no identity) or ForbidAsync (identity but not allowed) on the scheme, and the handler turns that into a 401, a 403 or a redirect.

The mistake I see is getting the middleware order wrong or registering authorisation in the wrong place: put UseAuthorization before UseAuthentication, or before UseRouting, and the decision is made with an anonymous user or without endpoint metadata. The senior point is simple: authentication only establishes facts about the caller; every security decision happens in authorisation, close to the endpoint."


The two concepts side by side

Authentication Authorisation
Question Who are you? What may you do?
Input Cookie, bearer token, API key, client certificate ClaimsPrincipal + endpoint + resource
ASP.NET Core piece IAuthenticationHandler, UseAuthentication IAuthorizationService, policies, UseAuthorization
Failure Challenge: 401 (API) or redirect to login (web) Forbid: 403 (API) or access-denied page (web)

The vocabulary

Term Meaning
Scheme A name ("Cookies", "Bearer") bound to a handler and its options
Handler Implements AuthenticateAsync, ChallengeAsync, ForbidAsync (and sign-in/out for cookies)
ClaimsPrincipal The user: one or more ClaimsIdentity objects, each a bag of claims (sub, name, role)
Default scheme Used by UseAuthentication and by [Authorize] without a scheme
Challenge / Forbid What the scheme does when authorisation fails for an anonymous / authenticated user

Middleware order that works

UseExceptionHandler -> UseHttpsRedirection -> UseRouting -> UseCors
  -> UseAuthentication -> UseAuthorization -> (rate limiter, antiforgery) -> endpoints

WebApplication adds routing, authentication and authorisation for you when the services are registered, but as soon as you call UseRouting or UseCors yourself you should place the auth calls explicitly so the order is obvious in code review.

Production example

In a [company] API, a new route group was mapped without RequireAuthorization() and the team had no fallback policy, so 6 endpoints were anonymous for [two weeks]. We added FallbackPolicy = RequireAuthenticatedUser() so every endpoint is protected unless it opts out with [AllowAnonymous], plus an integration test that calls every endpoint without a token and expects 401: [0] anonymous endpoints have slipped through since.

🔍 What the interviewer is checking

Checks that the candidate separates identity from permission and understands the concrete ASP.NET Core model rather than just decorating controllers with [Authorize].

Green flags

  • Explains 401 vs 403 in terms of challenge and forbid
  • Knows the handler produces a ClaimsPrincipal and does not block requests itself
  • States the middleware order and why routing must come first
  • Mentions a fallback policy

Red flags

  • Uses 'authentication' and 'authorisation' as synonyms
  • Thinks UseAuthentication rejects invalid tokens
  • Cannot say where HttpContext.User comes from

📚 Learn in depth

1. What authentication produces

Authentication does not decide anything; it produces facts. The output is an AuthenticateResult: success with an AuthenticationTicket (principal + properties + scheme), no result (no credential present), or failure (credential present but invalid, expired or tampered).

Request --> handler.AuthenticateAsync()
              |-- Success(ticket)  -> HttpContext.User = ticket.Principal
              |-- NoResult         -> HttpContext.User = anonymous principal
              '-- Fail(reason)     -> anonymous principal + logged reason

A failed token does not stop the request. That is deliberate: an endpoint marked [AllowAnonymous] should still work for a caller with an expired cookie.

2. The pipeline

Kestrel -> ... -> UseRouting (endpoint selected, metadata available)
        -> UseAuthentication (sets User from the default scheme)
        -> UseAuthorization (reads [Authorize], evaluates policies)
              |-- allowed     -> endpoint runs
              |-- no identity -> ChallengeAsync(scheme) -> 401 / redirect
              '-- denied      -> ForbidAsync(scheme)    -> 403 / redirect

UseAuthorization needs routing to have picked an endpoint, because the [Authorize] attribute is endpoint metadata. Before routing there is nothing to read.

3. Schemes and handlers

AddAuthentication("Bearer") sets the default scheme; since .NET 7, if exactly one scheme is registered it becomes the default automatically. Each AddXxx call registers options and a handler type. Handlers derive from AuthenticationHandler<TOptions> and are created per request, so they can use scoped services.

You can split the defaults: DefaultAuthenticateScheme, DefaultChallengeScheme (OpenID Connect redirects to the identity provider), DefaultSignInScheme (cookies persist the result). That split is exactly how a typical web app with an external login works.

4. Claims

A claim is a typed statement about the subject, issued by someone: sub=42, [email protected], role=Admin. ClaimsPrincipal.IsInRole looks at the identity's RoleClaimType, and User.Identity.Name reads its NameClaimType, which is why claim mapping (covered in the claims question) matters.

5. Status codes and redirects

For APIs the challenge is a 401 with a WWW-Authenticate header; for cookie-based web apps it is a 302 to the login page. Since .NET 10, the cookie handler returns 401/403 instead of redirecting for known API endpoints (for example [ApiController] actions and Minimal API endpoints returning JSON), which removes an old trap where an API call got an HTML login page with status 200.

Try it yourself

  1. Create a Minimal API with one [Authorize] endpoint and JWT bearer; call it with no token and inspect the 401 and WWW-Authenticate header.
  2. Swap UseAuthorization above UseAuthentication and observe that a valid token now gets 401.
  3. Turn on "Microsoft.AspNetCore.Authentication": "Debug" logging and read why a token failed.
  4. Write an endpoint that returns User.Claims as JSON and compare the claims for two schemes.
  5. Add a fallback policy and write an integration test with WebApplicationFactory that asserts every endpoint returns 401 anonymously, except an allow-list.

💻 Code

A minimal API with one authentication scheme, a fallback policy and the middleware in the right order.

// Program.cs (.NET 10, nullable enabled)
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;

var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) // default scheme
    .AddJwtBearer(options =>
    {
        // Issuer metadata and signing keys come from the identity provider.
        options.Authority = builder.Configuration["Auth:Authority"];
        options.Audience = builder.Configuration["Auth:Audience"];
    });

builder.Services.AddAuthorizationBuilder()
    // Every endpoint requires a signed-in user unless it opts out.
    .SetFallbackPolicy(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build());

var app = builder.Build();

app.UseHttpsRedirection();
app.UseAuthentication();   // sets HttpContext.User
app.UseAuthorization();    // decides, using endpoint metadata

app.MapGet("/health", () => Results.Ok()).AllowAnonymous();

app.MapGet("/me", (ClaimsPrincipal user) => new
{
    Id = user.FindFirstValue(ClaimTypes.NameIdentifier),
    Name = user.Identity?.Name,
    Claims = user.Claims.Select(c => new { c.Type, c.Value })
});

app.Run();

⚠ Common mistakes

  • Mistake: Calling UseAuthorization() before UseAuthentication(), or before routing. Why it is wrong: the policy is evaluated against an anonymous user (valid callers get 401) or without endpoint metadata, and in custom pipelines a misplaced branch can serve endpoints that never pass through authorisation at all. Instead: authentication first, then authorisation, both after routing and CORS, and an integration test that proves protected endpoints return 401 anonymously.
  • Mistake: Treating 401 and 403 as interchangeable. Why it is wrong: clients react differently; a 401 triggers a re-login or token refresh, and returning 401 for a permission failure can cause refresh loops, while returning 200 with an error body hides failures from monitoring. Instead: challenge when there is no identity, forbid when the identity lacks permission (or 404 when existence itself is sensitive).
  • Mistake: Expecting UseAuthentication to block bad tokens. Why it is wrong: it only sets User; an invalid token simply results in an anonymous request, so an endpoint without [Authorize] serves data to anyone. Instead: protect endpoints with [Authorize], RequireAuthorization() or a fallback policy.
  • Mistake: Relying on remembering [Authorize] on every controller and route group. Why it is wrong: one forgotten attribute exposes an endpoint anonymously, which under the Privacy Act can become a notifiable breach if personal information is returned. Instead: set a fallback policy and opt out explicitly with [AllowAnonymous].
  • Mistake: Doing permission checks inside a custom authentication handler. Why it is wrong: it mixes identity with decisions and breaks [AllowAnonymous] and policies. Instead: handlers produce claims; policies decide.
  • Mistake: Registering several schemes without choosing the default deliberately. Why it is wrong: [Authorize] uses only the default scheme, so a cookie user is rejected by a JWT default (or vice versa), and a policy scheme that forwards on a header can accept a weaker scheme than intended. Instead: set DefaultScheme / DefaultChallengeScheme explicitly, and name schemes on policies with AddAuthenticationSchemes where an endpoint needs a specific one.

🏛 Senior insight: trade-offs

Authentication is plumbing; authorisation is where the security bugs live. A senior answer keeps the handler thin (validate the credential, build claims) and puts every decision in policies, so the rules are testable and visible in one place. The fallback policy is the single cheapest control in ASP.NET Core: it turns 'forgot an attribute' from a breach into a 401.

Option When it fits Cost When not to
One scheme (JWT or cookies) Pure API or pure web app Lowest complexity When browsers and machine clients share endpoints
Cookie + OIDC challenge Server-rendered web app or BFF with external login Redirect flow, Data Protection keys to manage Machine-to-machine APIs
Several schemes + policy schemes API serving both a web front end and partners Harder to reason about the default If you can split into separate hosts instead

Measure it: log authentication failures by reason (Microsoft.AspNetCore.Authentication category) and alert on a spike, which usually means a key rollover or clock problem rather than an attack.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions middleware order Why: Checks they understand how the pipeline is built and why order matters in general
    How to answer

    Middleware is a component in the request pipeline: a RequestDelegate that receives the HttpContext, can do work, calls next to pass the request on, and can do more work when the response comes back. It can also short-circuit by not calling next. Use adds middleware that may call next; Run adds terminal middleware; Map branches the pipeline by path; UseWhen branches on a condition and rejoins, MapWhen branches without rejoining. Because each middleware wraps the next, order is behaviour: exception handling first, then HTTPS, static files, routing, CORS, authentication, authorisation and finally endpoints. Custom middleware can be convention-based (a class with InvokeAsync, created once as a singleton) or implement IMiddleware (resolved from DI per request). The trade-off: convention-based is the fastest default; IMiddleware is clearer when you need scoped dependencies.

  2. When: Candidate says [Authorize] can be bypassed by ordering mistakes Why: Checks they can diagnose middleware-order bugs in a real API
    How to answer

    All four are symptoms of a pipeline that doesn't match the documented order. I'd write the pipeline out from Program.cs and check it against exception handler → HTTPS → static files → routing → CORS → authentication → authorisation → endpoints. Auth bypass: UseAuthorization missing, before UseRouting, or the endpoint simply has no policy and there is no fallback policy. CORS: UseCors placed after authentication, so the preflight OPTIONS gets a 401 without CORS headers, or the policy isn't applied to the endpoint. Blank 500: UseExceptionHandler registered after the middleware that threw, AddProblemDetails not called, or the response had already started. Static files: files in wwwroot are public by design when UseStaticFiles runs first. I confirm each with Debug-level framework logs and lock the fix in with WebApplicationFactory tests.

  3. When: Candidate distinguishes 401 from 403 Why: Checks status code semantics beyond authentication
    How to answer

    The status code tells clients and infrastructure what happened before they read the body, so it must be exact.

    • Success: 200 OK with a body, 201 Created plus a Location header, 202 Accepted for work that finishes later, 204 No Content when there's nothing to return.
    • Client errors: 400 bad input, 422 well-formed but semantically invalid, 401 not authenticated vs 403 not allowed, 404 not found vs 410 gone, 409 conflicts with current state, 412 a precondition like If-Match failed, 429 rate limited with Retry-After.
    • Server errors: 500 our bug, 502 bad upstream response, 503 temporarily unavailable, 504 upstream timeout.

    The trade-off is precision versus consistency: pick a small, documented set and use it the same way in every service.

↩ Usually asked after

More in Authentication

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me