Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson1 / 13

    Module 1 · Identity and Token Foundations · Lesson 1 of 13

    Authentication, Authorization and Trust Boundaries

    Trace the denied request

    Alice reaches GET /orders with a demo identity but no orders.read permission. Bob has that permission. The health endpoint requires no credentials. Predict the three responses before reading the request matrix.

    Keep two decisions separate: authentication establishes the caller under a trust contract; authorization decides whether that caller may perform this action. The complete example uses an explicitly test-only header handler, so it tests policy behavior without claiming to validate real credentials.

    ASP.NET Core mental model

    When selected, authentication handlers validate credentials and, on success, produce a ClaimsPrincipal. Authorization evaluates policy requirements against the principal; its handlers can run even when authentication has not succeeded. Resource-based authorization can evaluate the target object and operation, which is important for ownership and tenant checks. Loading an object does not authorize access to it. See resource-based authorization.

    A claim is an issuer assertion, not permission by itself. Local policy decides whether a trusted claim is sufficient for a specific action.

    Threat-model categories

    • Credential theft: passwords, keys, cookies or refresh tokens leak.
    • Token substitution: a token for another issuer, audience or purpose is accepted.
    • Replay: a valid token or authorization response is reused.
    • Confused deputy: a trusted service is tricked into using its authority for the wrong caller.
    • Broken object authorization: an authenticated caller accesses another user's resource.
    • Information leakage: logs, errors or responses expose secrets or cross-tenant data.

    Scenario

    An interviewer asks whether a signed JWT makes an API secure. A complete answer is no: for a signed JWT access token, the API must validate the signature with a trusted issuer-bound key, an allowed algorithm, the expected issuer and audience, lifetime and token purpose, then enforce endpoint and resource authorization. Do not accept an ID token as an API access token. A valid signature alone does not prevent replay of a stolen bearer token. Transport security, key rotation, safe logging and incident response remain necessary. See JWT validation guidance and bearer-token protection.

    Worked example: 401 versus 403 in ASP.NET Core (.NET 10)

    The quickest way to explain the distinction is to trace a protected request. This teaching sample uses a minimal API hosted in memory with TestServer. It assumes a .NET 10 Web SDK project targeting net10.0, with implicit usings enabled and a compatible Microsoft.AspNetCore.TestHost 10.0.x package reference. TestServer sends requests in memory; this is not a test of TLS or a production deployment.

    The test-only handler trusts any supplied X-Demo-User header, including its user name and permission values. It performs no real credential validation: a caller can impersonate bob and grant themselves orders.read. Never deploy this handler. A real API needs a properly configured authentication scheme, such as JwtBearer, that establishes trust before policy evaluation. Three authorization rules apply:

    • a fallback policy that requires an authenticated user when no policy is selected from authorization metadata for a request reaching the authorization middleware;
    • an anonymous health endpoint whose AllowAnonymous metadata bypasses authorization enforcement, not authentication;
    • a named policy orders.read that explicitly requires both an authenticated user and the permission=orders.read claim.
    C#
    // In this sample, failed authorization triggers a challenge (401) without authentication, or a forbid (403) after authentication succeeds.
    // The DemoHeader scheme is a TEST-ONLY stand-in for JwtBearer or cookies so the example runs without an identity provider.
    using System.Security.Claims;
    using System.Text.Encodings.Web;
    using Microsoft.AspNetCore.Authentication;
    using Microsoft.AspNetCore.TestHost;
    using Microsoft.Extensions.Options;
    
    var builder = WebApplication.CreateBuilder();
    builder.WebHost.UseTestServer();
    builder.Logging.ClearProviders();
    builder.Services.AddAuthentication("DemoHeader")
        .AddScheme<AuthenticationSchemeOptions, DemoHeaderHandler>("DemoHeader", _ => { });
    builder.Services.AddAuthorizationBuilder()
        .AddPolicy("orders.read", p => p.RequireAuthenticatedUser().RequireClaim("permission", "orders.read"))
        // Unannotated endpoints require authentication; named/default policies enforce their own requirements.
        .SetFallbackPolicy(new Microsoft.AspNetCore.Authorization.AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build());
    
    var app = builder.Build();
    app.UseAuthentication();
    app.UseAuthorization();
    app.MapGet("/health", () => "ok").AllowAnonymous();
    app.MapGet("/me", (ClaimsPrincipal u) => $"sub={u.FindFirstValue("sub")}");
    app.MapGet("/orders", () => "3 orders").RequireAuthorization("orders.read");
    await app.StartAsync();
    var client = app.GetTestClient();
    
    async Task Call(string path, string? user)
    {
        var req = new HttpRequestMessage(HttpMethod.Get, path);
        if (user is not null) req.Headers.Add("X-Demo-User", user);
        var res = await client.SendAsync(req);
        var body = res.IsSuccessStatusCode ? await res.Content.ReadAsStringAsync() : "";
        Console.WriteLine($"{path,-8} user={user ?? "(none)",-28} -> {(int)res.StatusCode} {res.StatusCode} {body}".TrimEnd());
    }
    await Call("/health", null);
    await Call("/me", null);
    await Call("/me", "alice");
    await Call("/orders", "alice");
    await Call("/orders", "bob;orders.read");
    await app.StopAsync();
    
    sealed class DemoHeaderHandler(IOptionsMonitor<AuthenticationSchemeOptions> o, ILoggerFactory l, UrlEncoder e)
        : AuthenticationHandler<AuthenticationSchemeOptions>(o, l, e)
    {
        protected override Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            if (!Request.Headers.TryGetValue("X-Demo-User", out var v)) return Task.FromResult(AuthenticateResult.NoResult());
            var parts = v.ToString().Split(';');
            var claims = new List<Claim> { new("sub", parts[0]) };
            claims.AddRange(parts.Skip(1).Select(p => new Claim("permission", p)));
            var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, Scheme.Name));
            return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principal, Scheme.Name)));
        }
    
        protected override Task HandleChallengeAsync(AuthenticationProperties properties)
        {
            Response.StatusCode = 401;
            Response.Headers.WWWAuthenticate = Scheme.Name;
            return Task.CompletedTask;
        }
    }

    Expected output, reasoned from the sample and .NET 10 framework behavior:

    Text
    /health  user=(none)                       -> 200 OK ok
    /me      user=(none)                       -> 401 Unauthorized
    /me      user=alice                        -> 200 OK sub=alice
    /orders  user=alice                        -> 403 Forbidden
    /orders  user=bob;orders.read              -> 200 OK 3 orders

    What the output shows

    requestauthentication resultauthorization resultstatus
    /health, no userno credentialsauthorization bypassed by AllowAnonymous200
    /me, no userno credentialsfallback requirement fails; challenge401
    /me as alicealice (demo identity)authenticated-user requirement met200
    /orders as alicealice (demo identity)permission requirement fails; forbid403
    /orders as bob with orders.readbobpolicy met200

    In the default ASP.NET Core policy pipeline, failed authorization produces a challenge if the effective authentication result did not succeed, or a forbid if it did. Here the custom challenge writes 401 plus WWW-Authenticate: DemoHeader; the inherited forbid handler writes 403. AllowAnonymous lets /health proceed even though the authentication handler found no credentials. See the pinned .NET 10 policy evaluator.

    At the HTTP level, 401 means the request lacks valid authentication credentials for the target resource and must include an applicable WWW-Authenticate challenge. A 403 means the server refuses the request; it does not universally prove that authentication succeeded. Clients should follow the authentication scheme and error details, not blindly refresh on every 401 or retry a 403 unchanged. See RFC 9110, 401 and 403.

    Challenge and forbid are handler operations, not universal status-code guarantees. Cookie authentication can redirect browser requests; .NET 10 returns 401/403 by default for recognized API endpoints instead. A custom handler or result handler can change the response. See cookie authentication API behavior.

    Secure by default

    SetFallbackPolicy(... RequireAuthenticatedUser()) protects unannotated endpoints whose requests reach the authorization middleware. It is not a blanket rule added to every policy: /orders uses its named policy, not the fallback. A bare [Authorize] or RequireAuthorization() selects the default policy in the ordinary case without an explicit policy instance; the built-in default requires authentication. Named and explicit policies must include their own necessary requirements.

    AllowAnonymous() makes intentional public access reviewable, but does not stop authentication from running. Responses served before authorization middleware, such as static files served earlier in the pipeline, are outside the fallback policy. Keep restrictive defaults, review the whole pipeline, and enforce resource-specific permissions as well. See policy selection and fallback scope.

    Drawing the trust boundary in an interview

    For a typical "SPA plus API plus identity provider" question, say the boundaries out loud:

    Text
    [Browser / SPA] --(1) sign-in redirect--> [Identity provider]  authenticates users, issues tokens
          |                                          |
          |  (2) access token (aud = orders-api)     | signing keys published as JWKS
          v                                          v
    [Orders API]  validates token -> builds ClaimsPrincipal -> policy + resource checks -> [Database, tenant-filtered]
    • Boundary 1: the browser is untrusted. Anything it sends (IDs, tenant, roles in a body) is a claim to verify, not a fact.
    • Boundary 2: the API accepts only validated access tokens from configured trusted issuers and intended for this API. Obtain verification keys through trusted configuration or issuer metadata, not an arbitrary URL supplied by the token. The diagram is a boundary sketch, not the complete sign-in and token-exchange protocol.
    • Boundary 3: the database commonly sees the API's service identity, not the end user. Enforce tenant and ownership checks before returning or changing data; a successful database connection is not end-user authorization. Database-enforced isolation can provide an additional boundary.

    Common mistakes

    • Treating a blanket 404 response as a substitute for authorization or useful internal logging. HTTP permits 404 to conceal a forbidden resource, including another tenant's object, but the access check and safe diagnostic logging still matter. (See the resource authorization lesson.)
    • Assuming controller [Authorize] attributes also protect unrelated minimal API endpoints. Those endpoints need their own authorization metadata, inherited route-group requirements, or an appropriate fallback policy.
    • Treating a role claim from the client's request body as authorization.
    • Saying "we use JWT, so it is secure". JWT is a format; the security comes from validation and authorization.

    The public endpoint

    In the shown header-handler app, GET /health with no credentials returns 200. What explains that result?

    A AllowAnonymous prevents the authentication middleware from running.
    B AllowAnonymous bypasses authorization enforcement; the authentication handler can still run and return NoResult.
    C The fallback policy creates an authenticated principal for every health request.
    D A 200 response proves that the browser supplied valid credentials.
    Show answer

    Correct answer: B

    The health endpoint is deliberately public. AllowAnonymous affects authorization enforcement, not whether authentication can populate the request principal. The test-only header handler does not validate real credentials, and a successful public response is not proof of authentication.

    Explain the boundary

    Before the checks, name the handler operation and the policy selected for each request.

    1. "What is the difference between 401 and 403?"
    1. "Where does ASP.NET Core turn a token into a user?"
    1. "How do you make sure new endpoints are not public by accident?"
    1. "Is a claim a permission?"

    Stop here. Keep HTTP semantics distinct from the particular handler response.

    Compare your reasoning

    1. HTTP 401 means valid credentials for the target resource are missing and requires WWW-Authenticate. HTTP 403 means refusal, not necessarily successful authentication. In this sample, failed authorization challenges an unauthenticated caller with 401 and forbids an authenticated caller with 403; other schemes can respond differently.
    1. In the selected authentication handler, such as JwtBearer. Authentication middleware normally invokes the default authenticate scheme and assigns the resulting principal to HttpContext.User. Authorization's policy evaluator can invoke schemes specified by a policy, and application code can call AuthenticateAsync explicitly. Registering a handler alone does not mean it authenticates every request.
    1. Use an authenticated-user fallback for unannotated requests reaching authorization middleware, mark intended public endpoints with AllowAnonymous, and test the negative paths. Review named/default policies and middleware ordering too: the fallback neither augments those policies nor protects responses served earlier.
    1. No. A claim is an assertion by an issuer. Local policy decides whether that assertion, from that issuer, is enough for this action.

    Quick reference

    Review checklist

    • Trust boundary drawn.
    • Token holder and resource server named.
    • Negative paths tested.
    • Authorization described separately from authentication.
    • Recovery and rotation included, not postponed as operations details.
    Sign in to mark lessons done and keep your place in the course.Sign in

    TechInterviewNotes Editorial Team · Updated 28 Oct 2026 ·