AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 48

    Authentication and Authorization for SaaS Applications

    Northwind's instructor opened the operations panel and clicked "Send reminder." The request body included role: "supportlead" and organizationId: "contoso".

    Course progress0%
    Focus
    24 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    AI-Powered Full Stack Development · Lesson 48 · Full-Stack Security, Testing and Deployment

    Lesson Overview

    Northwind's instructor opened the operations panel and clicked "Send reminder." The request body included role: "support_lead" and organizationId: "contoso". Lesson 47's runCohortReminderWorkflow would have refused a learner and would have used whatever WorkflowScope the route handed it. The route, in the prototype, copied those two fields from JSON. Contoso's stalled learners were one forged body away from a Northwind browser.

    A second prototype stored the role inside a long-lived token and never read memberships again. An admin removed the instructor on Tuesday. The token still said instructor on Friday. The reminder started. PostgreSQL still had the membership row that should have stopped it. The token was a cache that had forgotten it was a cache.

    Authentication answers who is calling. Authorization answers what that caller may do to which records. This lesson builds the session TechLearningPro's workflow already assumes: a server-side session after a credential check, a membership load on every request, and an action matrix that produces WorkflowScope for the capstone. The browser does not appoint a role. A model does not appoint a role. A JSON web token, when you use one for a partner API, is a signed identity with a short life. It is not a substitute for the membership table in Relational Data Modeling with PostgreSQL.

    Planning assumptions:

    • The lab uses injected ports. No password hash, session secret, or signing key appears in source.
    • Browser sessions are opaque ids stored on the server. JSON Web Tokens are explained for partner APIs and are not the browser session.
    • Roles match the capstone: learner, instructor, support, support_lead, admin. Lesson 36's support_agent is the same person as support on this membership row.
    • Active organization is a column on the session row. Other routes ignore organizationId in the body.
    • Fixtures use northwind, contoso, and @northwind.test mailboxes. Nothing here is a production credential.

    Learning Objectives

    By the end of this lesson you will be able to:

    1. Separate authentication (who) from authorization (which action on which tenant).
    2. Explain why TechLearningPro's browser uses an opaque server session and why a partner API may use a short-lived JWT.
    3. Verify credentials through a port, and keep password hashes and session secrets out of the repository.
    4. Create a session id on the server, store it in an HttpOnly cookie, and rotate that id on sign-in and on organization switch.
    5. Load role and organization from memberships on each request, and ignore role fields in the body and in stale token claims.
    6. Fail closed when the cookie is missing, the session is expired, or the membership has been revoked.
    7. Map roles to actions such as reminder.start and reminder.approve.
    8. Apply object checks so a learner reads only their enrollment inside their organization.
    9. Require a CSRF header on cookie-authenticated state changes.
    10. Switch the active organization only after a membership check, and invalidate the previous session id.
    11. Build WorkflowScope for lesson 47 from the principal, never from the request body.
    12. Return the same invalid_credentials outcome for an unknown mailbox and a wrong password.
    13. State what a JWT must carry (iss, aud, sub, exp) and what it must not be trusted to carry alone (a role for the rest of the week).
    14. Keep session cookies, bearer tokens, and passwords out of logs and out of model prompts.
    15. Test a forged role, a revoked membership, a learner approval attempt, and a missing CSRF header without a real identity provider.

    Prerequisites

    What is Authentication and Authorization for SaaS Applications?

    Authentication is the check that a secret the caller possesses matches an account you issued. For the TechLearningPro browser that secret is a password checked against a stored password hash, or a completed single sign-on assertion your identity adapter has already validated. The result is a user id. Authorization is the later check that this user id holds a membership in an organization and that the membership's role includes the action the route implements.

    The purpose is to stop treating "logged in" as "allowed." A learner is logged in. A learner must not approve a cohort reminder. An instructor is logged in at Northwind. An instructor must not read Contoso's enrollments. A signed token proves the signer produced claims at a moment in time. It does not prove the membership row still exists.

    SaaS products learned this split in ordinary web apps before AI features existed. Banks separate "this is the customer" from "this customer may wire this amount." Amazon, Google, and Microsoft consumer and cloud consoles bind a session to an account, then evaluate policy per API. Netflix profiles are not payment authorities. Healthcare portals authenticate a clinician and still check the patient relationship. TechLearningPro adds a model beside those checks. The model is another caller that does not get a session of its own.

    TermMeaning in this lesson
    PrincipalUser id, active organization, role, session id
    SessionServer row plus an opaque cookie value
    MembershipRow in memberships for one user and one organization
    ActionA named permission such as reminder.approve
    CSRF tokenA second secret for cookie-authenticated writes
    JWTSigned claims for a partner or service client
    WorkflowScopeThe object lesson 47 already accepts

    Why Do We Need It?

    text
    Browser JSON { role, organizationId }
    |
    v
    Route copies the body into WorkflowScope
    |
    v
    Reminder runs as support_lead in the wrong tenant
    |
    v
    Fix: session cookie -> session row -> membership -> action matrix -> scope
    |
    v
    Forged role is ignored. Revoked membership fails closed. Lesson 47 sees a real scope.

    Without a server session, every AI route invents identity. The knowledge assistant, the support proposal, and the reminder workflow then disagree about who the caller is. With a session that never reloads membership, revocation is theater. With a role inside the token and no object check, a learner who can call GET /api/enrollments/:id reads another learner's row.

    The benefits are ordinary and worth the table:

    FailureControl in this lesson
    Body sets roleRole is loaded from memberships
    Removed instructor keeps accessMembership is read per request
    Learner approves mailAction matrix returns forbidden
    Cookie sent from another siteSameSite plus a CSRF header on writes
    Session id fixed before loginNew session id after a successful credential check
    Partner token lives for a week with a roleShort exp, audience check, membership reload on writes

    Real World Example

    TechLearningPro sells one application to many academies. Northwind instructors start reminders. Northwind support leads approve them. Contoso admins invite Contoso staff. A learner in either academy opens lessons and their own enrollments. Google-style workspace products, Microsoft 365 tenants, and banking portals all treat the directory as the authority and the browser as a hint. Amazon's account pages do not accept a customer-supplied seller id as proof of ownership. Healthcare apps that did accept a patient id from the query string disclosed the wrong chart.

    The AI surfaces sit on the same principal. The support console in Agentic AI Concepts and Tool-Using Systems builds its caller from the session. The reminder in lesson 47 refuses learner. This lesson is the code that makes those assumptions true before either feature runs.

    Internal Working

    1. The sign-in route reads email and password. It does not read role or organizationId.
    2. CredentialPort.verify returns a user id or invalid_credentials. Unknown mailbox and wrong password share that reason.
    3. The server creates a new session id, stores userId, expiry, and a CSRF secret, and sets the cookie. The active organization is the user's sole membership, or empty until they pick one when they have several.
    4. On later requests the API reads the cookie, loads the session, and rejects missing, expired, and unknown ids as unauthenticated.
    5. It loads the membership for (userId, activeOrganizationId). A missing row is forbidden even if the session row remains.
    6. The route names an action. authorize checks the role matrix. Object helpers then check tenant and owner.
    7. State-changing routes compare the CSRF header to the session secret with a constant-time compare port.
    8. Organization switch checks the target membership, writes a new session id, and deletes the old id.
    9. toWorkflowScope copies tenant, user, and role from the principal. Lesson 47 receives that object and still enforces its own role gate.
    10. Sign-out deletes the session row. Logs record user id and reason. They omit the cookie, the password, and the CSRF secret.

    Architecture

    flowchart TB
      subgraph browser [Browser]
        Cookie[HttpOnly session cookie]
        Form[Email and password]
      end
    
      subgraph api [TechLearningPro API]
        Login[Sign-in route]
        Load[Load session and membership]
        Authz[Action matrix and object check]
        Scope[WorkflowScope]
      end
    
      subgraph data [PostgreSQL]
        Users[users and password hashes]
        Sessions[sessions]
        Members[memberships]
      end
    
      subgraph later [Later features]
        Flow[Lesson 47 reminder]
        Model[Model port]
      end
    
      Form --> Login
      Login --> Users
      Login --> Sessions
      Cookie --> Load
      Load --> Sessions
      Load --> Members
      Load --> Authz
      Authz --> Scope
      Scope --> Flow
      Flow --> Model

    There is no edge from Form to Members that writes a role. There is no edge from Model to Sessions.

    text
    Request
    -> cookie present? no -> 401 unauthenticated
    -> session row fresh? no -> 401 unauthenticated
    -> membership for active org? no -> 403 forbidden
    -> action allowed for role? no -> 403 forbidden
    -> object in this org and, for learners, this user? no -> 404
    -> CSRF header on writes? no -> 403 csrf
    -> handler, then lesson 47 if the action is a reminder

    Trust boundaries: the browser is untrusted. The password hash store is reached only through CredentialPort. The session secret that signs nothing in this design stays in the session table, not in the client. A JWT public key, when a partner client exists, stays in the composition root. PostgreSQL memberships is the authorization source. The model is untrusted and is not on this path.

    Deep Dive

    Sessions for the browser

    An opaque session id is a random value the server stores and the browser echoes. The cookie attributes are part of the design:

    AttributeLab choiceWhy
    HttpOnlyYesScript on the page cannot read the id
    SecureYes in deployed environmentsThe cookie rides only with HTTPS
    SameSiteLaxCross-site form posts omit the cookie
    Path/The API and the app share one host
    Name__Host-tlp_sessionHost-only cookie, no Domain attribute

    SameSite=Lax blocks many cross-site posts and still sends the cookie on a top-level navigation. State-changing routes therefore also require the CSRF header. A missing header is csrf, which is forbidden for the client and distinct in logs.

    The session row holds id, userId, activeOrganizationId, csrfSecret, expiresAt. The role is not stored on that row. Storing the role there recreates the Friday token bug inside the session table. Expiry in the lab is 12 hours of inactivity, implemented as expiresAt extended on use up to an absolute 7-day cap. Production numbers belong in a reviewed constant, SESSION_POLICY_VERSION = "browser-session-v1".

    Rotation: sign-in always inserts a new id. Organization switch inserts a new id and deletes the previous one so a stolen pre-switch cookie dies. Sign-out deletes the row. Password reset, which this lesson does not implement, must delete every session for that user id.

    JWT for partner APIs

    A JSON Web Token is three parts: a header, claims, and a signature. Verification checks the signature against a key id you trust, then checks iss, aud, and exp. TechLearningPro's partner audience is the constant tlp-api. A token whose aud is something else is rejected. The algorithm is pinned in the verifier. A token that asks for the none algorithm fails. The lab does not ship a verifier implementation. It ships the claims check so the rules are testable with a parsed object the test builds:

    text
    required: iss = "https://login.techlearningpro.test", aud = "tlp-api", exp in the future, sub = user id
    ignored for authorization: role, organizationId

    Access tokens in this design live for minutes. A refresh token is stored as a hash on the server, rotated on use, and family-revoked if a retired refresh token reappears. That machinery is named here so you do not put a week-long role claim in the browser. The browser keeps the opaque session. Partner servers present the access token. Mutating partner routes still load memberships.

    Do not place the signing key, a sample private key, or a live token in the repository. The composition root receives a key handle the same way AI Integration Architecture receives a model credential: feature code sees a port, not the secret.

    The membership matrix

    RoleActions
    learnerenrollment.read_own
    instructorenrollment.read_tenant, reminder.start
    supportenrollment.read_tenant
    support_leadenrollment.read_tenant, reminder.start, reminder.approve
    adminthose three, plus org.members.invite

    admin is an organization admin. A platform operator who can see every tenant is a different role, absent from this matrix, and absent from the application database role. Lesson 49 keeps that break-glass path out of the request pool.

    Object rules sit beside the matrix. enrollment.read_own also requires row.userId === principal.userId and row.organizationId === principal.organizationId. enrollment.read_tenant requires the organization match and does not require the owner match. A miss is not_found so the handler does not reveal that the other tenant's id exists. Lesson 49 generalizes this predicate. This lesson establishes it for enrollments and for the reminder scope.

    CSRF, enumeration, and lockout

    Sign-in returns invalid_credentials for both unknown email and a bad password. The message does not say which factor failed. The route is rate-limited per IP and per mailbox in the composition root. This package accepts a RateLimitPort and stops at rate_limited before CredentialPort when the port says so. Lockout of the account itself is a product decision: TechLearningPro slows the route rather than permanently locking a mailbox an attacker can trigger. Document that choice so support does not expect a locked flag this package does not set.

    CSRF secrets are compared through safeEqual. A plain === is the wrong tool for secrets because it can return early. Tests inject safeEqual that still returns a boolean. Production uses a constant-time compare from the platform crypto library. The lesson does not paste a home-grown bitwise loop for you to copy incorrectly.

    What the model is allowed to know

    Prompts may include a display name and an organization display name when the product needs them. They do not include the session id, the CSRF secret, the password, the password hash, or a bearer token. Authorization decisions are made before toWorkflowScope returns. Lesson 47 then repeats the role check. Two checks are cheap. One check hidden in a prompt is not a check.

    Code Examples

    Place the package at packages/identity/src/. Tests construct ports. They do not read process.env.

    Simple example: actions and the matrix

    packages/identity/src/authz.ts

    typescript
    export const AUTHZ_VERSION = "saas-authz-v1";
    export type Role = "learner" | "instructor" | "support" | "support_lead" | "admin";
    export type Action =
    | "enrollment.read_own"
    | "enrollment.read_tenant"
    | "reminder.start"
    | "reminder.approve"
    | "org.members.invite";
    const MATRIX: Record<Role, readonly Action[]> = {
    learner: ["enrollment.read_own"],
    instructor: ["enrollment.read_tenant", "reminder.start"],
    support: ["enrollment.read_tenant"],
    support_lead: ["enrollment.read_tenant", "reminder.start", "reminder.approve"],
    admin: ["enrollment.read_tenant", "reminder.start", "reminder.approve", "org.members.invite"],
    };
    export function roleAllows(role: Role, action: Action): boolean {
    return MATRIX[role].includes(action);
    }

    The matrix is the review artifact. A new action is a code change, not a string the browser sends.

    Intermediate example: session establishment

    packages/identity/src/session.ts

    typescript
    import { roleAllows, type Action, type Role } from "./authz.js";
    export type Failure =
    | "invalid_credentials"
    | "rate_limited"
    | "unauthenticated"
    | "forbidden"
    | "csrf"
    | "not_found";
    export interface CredentialPort {
    verify(
    email: string,
    password: string,
    ): Promise<{ ok: true; userId: string } | { ok: false; reason: "invalid_credentials" }>;
    }
    export interface Membership {
    organizationId: string;
    role: Role;
    }
    export interface MembershipPort {
    listForUser(userId: string): Promise<Membership[]>;
    }
    export interface SessionRecord {
    id: string;
    userId: string;
    activeOrganizationId: string;
    csrfSecret: string;
    expiresAt: number;
    }
    export interface SessionStore {
    insert(record: SessionRecord): Promise<void>;
    get(id: string): Promise<SessionRecord | null>;
    delete(id: string): Promise<void>;
    }
    export interface Principal {
    sessionId: string;
    userId: string;
    organizationId: string;
    role: Role;
    }
    export interface WorkflowScope {
    tenantId: string;
    userId: string;
    role: Role;
    }
    const SESSION_MS = 12 * 60 * 60 * 1000;
    export async function signIn(
    creds: CredentialPort,
    members: MembershipPort,
    sessions: SessionStore,
    ids: { sessionId: string; csrfSecret: string },
    input: { email: string; password: string; now: number },
    ): Promise<{ ok: true; session: SessionRecord; csrfSecret: string } | { ok: false; reason: Failure }> {
    const verified = await creds.verify(input.email.trim().toLowerCase(), input.password);
    if (!verified.ok) return { ok: false, reason: "invalid_credentials" };
    const memberships = await members.listForUser(verified.userId);
    const active = memberships[0];
    if (!active) return { ok: false, reason: "forbidden" };
    const session: SessionRecord = {
    id: ids.sessionId,
    userId: verified.userId,
    activeOrganizationId: active.organizationId,
    csrfSecret: ids.csrfSecret,
    expiresAt: input.now + SESSION_MS,
    };
    await sessions.insert(session);
    return { ok: true, session, csrfSecret: session.csrfSecret };
    }
    export async function principalFromSession(
    sessions: SessionStore,
    members: MembershipPort,
    input: { sessionId: string; now: number },
    ): Promise<{ ok: true; principal: Principal } | { ok: false; reason: Failure }> {
    const session = await sessions.get(input.sessionId);
    if (!session || session.expiresAt <= input.now) return { ok: false, reason: "unauthenticated" };
    const memberships = await members.listForUser(session.userId);
    const membership = memberships.find((row) => row.organizationId === session.activeOrganizationId);
    if (!membership) return { ok: false, reason: "forbidden" };
    return {
    ok: true,
    principal: {
    sessionId: session.id,
    userId: session.userId,
    organizationId: membership.organizationId,
    role: membership.role,
    },
    };
    }
    export function authorize(principal: Principal, action: Action): { ok: true } | { ok: false; reason: "forbidden" } {
    return roleAllows(principal.role, action) ? { ok: true } : { ok: false, reason: "forbidden" };
    }
    export function toWorkflowScope(principal: Principal): WorkflowScope {
    return {
    tenantId: principal.organizationId,
    userId: principal.userId,
    role: principal.role,
    };
    }

    signIn takes ids from the caller so tests stay deterministic and the package does not read a secret. The composition root generates those ids with the platform CSPRNG and sets the cookie. Feature code never logs ids.csrfSecret.

    Enterprise example: CSRF, object check, organization switch

    packages/identity/src/guards.ts

    typescript
    import { authorize, type Failure, type MembershipPort, type Principal, type SessionRecord, type SessionStore } from "./session.js";
    export interface EnrollmentRow {
    id: string;
    organizationId: string;
    userId: string;
    }
    export function assertCsrf(
    session: SessionRecord,
    header: string | undefined,
    safeEqual: (a: string, b: string) => boolean,
    ): { ok: true } | { ok: false; reason: "csrf" } {
    if (!header || !safeEqual(header, session.csrfSecret)) return { ok: false, reason: "csrf" };
    return { ok: true };
    }
    export function readEnrollment(
    principal: Principal,
    row: EnrollmentRow | null,
    ): { ok: true; row: EnrollmentRow } | { ok: false; reason: Failure } {
    if (!row || row.organizationId !== principal.organizationId) return { ok: false, reason: "not_found" };
    const action = principal.role === "learner" ? "enrollment.read_own" : "enrollment.read_tenant";
    const allowed = authorize(principal, action);
    if (!allowed.ok) return { ok: false, reason: "forbidden" };
    if (action === "enrollment.read_own" && row.userId !== principal.userId) return { ok: false, reason: "not_found" };
    return { ok: true, row };
    }
    export async function switchOrganization(
    members: MembershipPort,
    sessions: SessionStore,
    current: SessionRecord,
    input: { organizationId: string; nextSessionId: string; now: number },
    ): Promise<{ ok: true; session: SessionRecord } | { ok: false; reason: Failure }> {
    const memberships = await members.listForUser(current.userId);
    const next = memberships.find((row) => row.organizationId === input.organizationId);
    if (!next) return { ok: false, reason: "forbidden" };
    const rotated: SessionRecord = {
    ...current,
    id: input.nextSessionId,
    activeOrganizationId: next.organizationId,
    expiresAt: input.now + 12 * 60 * 60 * 1000,
    };
    await sessions.insert(rotated);
    await sessions.delete(current.id);
    return { ok: true, session: rotated };
    }

    A body field named organizationId never reaches switchOrganization unless the route explicitly treats the call as a switch and has already passed CSRF. Reminder and enrollment routes do not call this function.

    Tests

    packages/identity/src/session.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { readEnrollment } from "./guards.js";
    import { authorize, principalFromSession, signIn, toWorkflowScope, type Membership, type SessionRecord } from "./session.js";
    const memory = () => {
    const rows = new Map<string, SessionRecord>();
    return {
    rows,
    async insert(record: SessionRecord) {
    rows.set(record.id, record);
    },
    async get(id: string) {
    return rows.get(id) ?? null;
    },
    async delete(id: string) {
    rows.delete(id);
    },
    };
    };
    test("sign-in ignores a caller who would have sent a role", async () => {
    const sessions = memory();
    const result = await signIn(
    { async verify() { return { ok: true, userId: "usr_instructor" }; } },
    { async listForUser(): Promise<Membership[]> { return [{ organizationId: "northwind", role: "instructor" }]; } },
    sessions,
    { sessionId: "ses_test_1", csrfSecret: "csrf_test_1" },
    { email: "instructor@northwind.test", password: "fixture-password", now: 1_000 },
    );
    assert.equal(result.ok, true);
    if (!result.ok) return;
    const loaded = await principalFromSession(sessions, {
    async listForUser(): Promise<Membership[]> {
    return [{ organizationId: "northwind", role: "instructor" }];
    },
    }, { sessionId: "ses_test_1", now: 1_000 });
    assert.equal(loaded.ok, true);
    if (!loaded.ok) return;
    assert.deepEqual(toWorkflowScope(loaded.principal), {
    tenantId: "northwind",
    userId: "usr_instructor",
    role: "instructor",
    });
    assert.equal(authorize(loaded.principal, "reminder.approve").ok, false);
    });
    test("revoked membership fails closed", async () => {
    const sessions = memory();
    await sessions.insert({
    id: "ses_test_2",
    userId: "usr_instructor",
    activeOrganizationId: "northwind",
    csrfSecret: "csrf_test_2",
    expiresAt: 5_000,
    });
    const loaded = await principalFromSession(sessions, { async listForUser() { return []; } }, {
    sessionId: "ses_test_2",
    now: 1_000,
    });
    assert.deepEqual(loaded, { ok: false, reason: "forbidden" });
    });
    test("learner cannot read another learner enrollment", () => {
    const result = readEnrollment(
    { sessionId: "ses_test_3", userId: "usr_learner", organizationId: "northwind", role: "learner" },
    { id: "enr_2", organizationId: "northwind", userId: "usr_other" },
    );
    assert.deepEqual(result, { ok: false, reason: "not_found" });
    });

    Add tests before you call the lesson done: expired expiresAt returns unauthenticated; assertCsrf fails when the header is absent; switchOrganization to contoso without a Contoso membership returns forbidden and leaves the old session id in the store; a learner principal fails reminder.start. The fixture password string stays inside the test that needs a credential port. Production verification is a hash check behind CredentialPort. Do not copy fixture-password into a config file.

    Architecture Diagram

    text
    Browser
    -> POST /api/session CredentialPort, then sessions insert, Set-Cookie
    -> POST /api/reminders cookie + CSRF + membership + reminder.start
    -> WorkflowScope lesson 47
    -> POST /api/session/org membership check, rotate session id
    -> DELETE /api/session delete row
    Partner API
    -> Authorization bearer
    -> verify iss, aud, exp, signature
    -> load membership anyway for writes
    sequenceDiagram
      participant B as Browser
      participant A as API
      participant M as memberships
      participant W as Lesson 47
      B->>A: POST /api/reminders cookie and CSRF
      A->>M: role for user and active org
      M-->>A: instructor
      A->>A: reminder.start allowed
      A->>W: WorkflowScope tenant northwind
      W-->>B: awaiting_approval or unauthorized

    Real-Time Enterprise Example

    In production the composition root owns cookie flags, the CSPRNG, the password hasher, and the optional JWT verifier. Northwind's instructor signs in. The only membership is Northwind, so the session's active organization is Northwind. They start a reminder. authorize allows reminder.start. toWorkflowScope yields { tenantId: "northwind", userId, role: "instructor" }. Lesson 47 runs. A support lead in the same organization later approves, because their membership includes reminder.approve.

    A learner who copies the reminder request in the browser's network panel still sends their own cookie. The membership load returns learner. reminder.start is forbidden. The workflow function is not called. If that learner also pastes role: "support_lead" into the JSON, the sign-in and reminder parsers never read it.

    Contoso is unreachable until the user has a Contoso membership and calls the switch route. Switching rotates the session id. The Northwind cookie value no longer loads a row. AI prompts for the reminder receive the template id path from lesson 47. They do not receive the cookie.

    Performance Optimization

    Membership reads happen on every authenticated request. That is a deliberate cost.

    • Index memberships (user_id, organization_id). The lookup is a point read, not a scan.
    • Cache the membership for the request only. A process-wide cache must expire in seconds and must drop on revocation. A 12-hour cache recreates the stale token bug.
    • Do not call the model, and do not open the reminder workflow, before authorization returns. Unauthorized traffic must be cheap.
    • Session lookup is by primary key. Keep session rows narrow. Do not store the user agent essay or the last prompt in that row.
    • Rate-limit sign-in before the password hasher. A memory-hard hash is supposed to be slow. Attackers should hit the limiter first. Legitimate sign-in pays the hash once.
    • JWT verification uses a cached public key by kid. Fetching a key document on every call adds latency and a new failure mode. Cache with a short TTL and a pinned issuer.

    Illustrative, not a benchmark: one membership read plus one session read per API call. A reminder that fails authorization performs neither a model call nor an enrollment lookup.

    Security

    • Passwords are verified by CredentialPort. Production stores a password hash from a memory-hard algorithm such as argon2id. The package never sees the hash.
    • Session ids and CSRF secrets are generated outside this package. Tests pass fixed fixture ids. Those fixture strings are not production secrets.
    • Cookies are HttpOnly, Secure, SameSite=Lax, and host-prefixed. JavaScript on the page cannot copy the session id into a prompt.
    • Authorization uses the live membership. JWT role claims are ignored when they appear.
    • Object access for learners is not_found on a mismatch so ids are not an oracle.
    • Logs may include user id, organization id, action, and failure reason. They omit passwords, cookies, CSRF secrets, authorization headers, and password hashes.
    • Sign-in responses do not distinguish unknown users from bad passwords.
    • The model cannot mint a principal. If a later feature wants the model to "act as the user," it reuses this principal and the action matrix.

    OWASP themes that match: identification and authentication failures, broken access control, and security misconfiguration of cookies. The controls are the membership load, the matrix, the object check, and the cookie flags.

    Common Mistakes

    1. Copying role from JSON into WorkflowScope. Symptom: a learner starts a reminder. Cause: the client was treated as the directory. Fix: principalFromSession and toWorkflowScope.
    2. Trusting a week-old role claim. Symptom: a removed instructor still approves. Cause: the token was the only read. Fix: load memberships on the request. Keep JWT lifetimes short for partner calls.
    3. Putting the role on the session row and skipping membership. Symptom: revocation waits for expiry. Cause: the session became a second directory. Fix: session stores user id and active organization only.
    4. Skipping CSRF because SameSite is set. Symptom: a top-level or legacy cross-site flow still posts. Cause: Lax was treated as a complete control. Fix: assertCsrf on state changes.
    5. Returning "unknown email" vs "bad password". Symptom: a mailbox list grows from the sign-in form. Cause: two different reasons. Fix: one invalid_credentials.
    6. Logging the cookie to debug a 401. Symptom: session ids land in the log vendor. Cause: the header was dumped. Fix: log the reason and the user id after a successful load only.
    7. Letting the model see the bearer token "for context". Symptom: a prompt transcript is a credential store. Cause: the whole request was serialized. Fix: prompts receive display fields the product chose, never the cookie or the Authorization header.
    8. Using === on the CSRF secret. Symptom: a timing gap on the compare. Cause: string equality returns early. Fix: the safeEqual port backed by a constant-time compare.
    9. Hiding cross-tenant rows as 403 with the row's id echoed. Symptom: attackers learn which ids exist. Cause: the handler loaded the row, then complained. Fix: organization mismatch is not_found and the body has no foreign id.
    10. One session id for the life of the password. Symptom: a stolen pre-login cookie becomes authenticated. Cause: the id was minted before credentials and reused. Fix: new id inside signIn, and again on organization switch.
    11. Accepting alg: none or an unexpected issuer. Symptom: a self-signed partner token passes. Cause: the library's default was left open. Fix: pin algorithm, issuer, and audience in the verifier you keep in the composition root.
    12. Caching "is instructor" in local storage for the UI and also for the API. Symptom: the button hides, the API still allows, or the reverse. Fix: the UI may hint. authorize is the API.

    Best Practices

    1. Keep AUTHZ_VERSION next to the matrix.
    2. Generate session ids in the composition root.
    3. Store sessions on the server for the browser.
    4. Set HttpOnly, Secure, and SameSite on the cookie.
    5. Reload membership on every request.
    6. Ignore role and organizationId on ordinary bodies.
    7. Rotate the session id on sign-in and on organization switch.
    8. Delete the session row on sign-out.
    9. Delete every session for a user when the password changes.
    10. Use one failure reason for bad sign-in.
    11. Rate-limit sign-in in front of the password hasher.
    12. Compare CSRF secrets with a constant-time function.
    13. Map routes to actions, not to "any logged-in user."
    14. Return not_found when the object is outside the principal's organization.
    15. Build WorkflowScope only from Principal.
    16. Keep JWT access tokens short and audience-pinned.
    17. Pin the signature algorithm and reject none.
    18. Omit cookies and passwords from logs and prompts.
    19. Test revocation, forged role, learner approval, and missing CSRF.
    20. Leave platform-wide cross-tenant access out of this matrix.
    21. Hash passwords with a memory-hard algorithm behind the port.
    22. Do not invent a second role list for AI routes.
    23. Treat the UI's hidden button as a convenience.
    24. Document browser-session-v1 expiry numbers in the same review as the matrix.

    Interview Questions & Answers

    Beginner

    1. What is the difference between authentication and authorization? Authentication establishes the user id. Authorization decides whether that user may perform an action on a tenant and an object. A valid session is not permission to approve a reminder.

    2. Why does the browser use a server session? The server can delete the row when a membership changes or the user signs out. The cookie is only an id. The role lives in memberships, which the next request will read.

    3. Why do sign-in errors look the same for a bad password and an unknown email? Distinct errors let a caller build a list of mailboxes. invalid_credentials gives the user a way to retry without confirming which factor failed.

    Intermediate

    1. What do you check on a JWT before you trust it? Signature with a pinned algorithm and key id, then issuer, audience, and expiry. You still load membership for authorization. A role claim is not the directory.

    2. Why rotate the session id on login? An id created before the password check can be planted by someone else. Replacing it after success means the authenticated cookie is one the server just minted. Organization switch rotates again so the previous cookie dies.

    3. What does the CSRF header add beyond SameSite? SameSite=Lax withholds the cookie on many cross-site posts and still sends it on some navigations. The header proves the page's script, which can read the CSRF value from a same-origin response, is the caller. The session cookie itself stays HttpOnly.

    Senior

    1. Where do you enforce learner versus instructor on enrollments? The matrix picks read_own or read_tenant. readEnrollment then requires the organization match for both, and the user match for learners. A foreign organization is not_found.

    2. How do you revoke an instructor who still holds a cookie? Delete or update the membership. The next request's principalFromSession finds no matching membership and returns forbidden. Waiting for cookie expiry is the bug.

    3. How should a partner API differ from the browser? The partner presents a short-lived bearer token. You verify signature, issuer, audience, and expiry. Writes still resolve sub to a user and load memberships. You do not copy the browser session cookie into a service.

    Architect

    1. Why is a platform superuser absent from this matrix? An organization admin is a tenant role. A role that can read every academy is a break-glass operator with a separate audit path and a separate database role. Putting it on the application pool makes every bug cross-tenant. Lesson 49 keeps that path out of request connections.

    2. How does this session meet the lesson 47 capstone? toWorkflowScope supplies tenantId, userId, and role. The capstone still rejects learner. The route must not call the workflow when authorize fails, so a forbidden reminder does not spend a model call.

    3. What is your stance on access tokens in local storage? The browser session is a host-prefixed HttpOnly cookie, so page script cannot exfiltrate it into a prompt or a third-party call. A design that stores a long-lived access token where script can read it turns every XSS into a session theft. Partner tokens stay on servers.

    4. How do you test this without an identity provider? Inject CredentialPort, MembershipPort, and SessionStore. Assert forged roles never enter the API, revocation returns forbidden, learners fail reminder.approve, and CSRF fails closed. Contract-test the real hasher and cookie flags in the composition root.

    5. What belongs in logs? User id, organization id, action, and the typed reason. The password, cookie, CSRF secret, and Authorization header stay out. A 401 before the session loads has a request id and no user id.

    6. Why is object hiding a 404? A 403 that repeats the enrollment id tells the caller the row exists in some tenant. not_found matches the product rule that ids outside the principal's scope are not resources they can address.

    7. How do multiple organizations work? listForUser can return several memberships. Sign-in activates the first only when you have defined an order. The supported path is an explicit switch that checks membership and rotates the session. Other routes ignore a body organization id.

    8. What fails if the password hasher is fast? Attackers who obtain the hash database guess passwords cheaply. A memory-hard algorithm raises that cost. The sign-in route still rate-limits so the hasher is not an open CPU bill.

    9. Can the AI approve a reminder by saying so? No. Approval is reminder.approve on a human principal, then lesson 45's ticket. Model text is not a principal and not an approval.

    10. What is session fixation in one sentence? It is authenticating a session id the attacker already knew. Minting a new id after the credential check closes it.

    11. Which cookie flag stops page JavaScript from reading the session? HttpOnly. Secure limits transport to HTTPS. SameSite limits when the browser attaches the cookie. You want all three, plus CSRF on writes.

    Knowledge Check

    1. What problem does this capability solve?

    It binds every TechLearningPro request to a user and a membership the server loaded, and it turns that principal into the WorkflowScope lesson 47 already requires. A JSON role cannot appoint a support lead, and a removed instructor cannot keep a stale role.

    2. What alternatives exist, and when would you choose each?

    Use an opaque server session for the browser, where immediate revocation and organization switch matter. Use a short-lived JWT for a partner service that cannot hold your cookie, and still load membership on writes. Use the identity provider's assertion only at sign-in, through an adapter, then issue your own session. A long-lived token whose role claim is the only authorization fits a demo and fails the Friday revocation story.

    3. Which data, identity, and trust boundaries matter?

    The browser is untrusted. CredentialPort is the only password boundary. memberships is the role boundary. The session row is the revocation boundary for the cookie. CSRF is the boundary for cookie-authenticated writes. The model is outside this flow. Logs are a data boundary: they do not get secrets.

    4. What can fail, and how should the system respond?

    Missing or expired sessions are unauthenticated. Missing memberships, disallowed actions, and illegal organization switches are forbidden. Cross-tenant or cross-learner objects are not_found. A bad CSRF header is csrf. Bad sign-in is invalid_credentials without a user oracle. None of these call the reminder workflow.

    5. How would you test quality, security, performance, and cost?

    Tests cover sign-in to a Northwind instructor scope, a revoked membership, a learner reading someone else's enrollment, a missing CSRF header, and a refused organization switch. Security review checks cookie flags in the composition root and confirms prompts cannot receive the cookie. Performance review checks that forbidden returns before a model call. Cost review checks that failed authorization does not call CredentialPort again and does not call the model at all.

    Practical Exercise

    Build the identity slice: signIn, principalFromSession, authorize, readEnrollment, assertCsrf, and switchOrganization. Use in-memory ports. Do not create a cloud identity account, and do not commit a password hash or a signing key.

    1. Draw the request path from cookie to WorkflowScope. Mark the model as unable to write a session.
    2. Implement the package as specified, including the action matrix.
    3. Add the tests in this lesson plus expiry, CSRF failure, learner reminder.start, and a refused switch that keeps the old session.
    4. Write six rows: control, owner, evidence. Include credential verification, membership reload, the matrix, CSRF, session rotation, and log redaction.
    5. State the HTTP status you would map for unauthenticated, forbidden, not_found, and csrf.
    6. Show a reminder request whose JSON contains role: "support_lead" and explain why the scope role is still the membership role.

    Challenge. A user belongs to Northwind as instructor and Contoso as learner. They switch to Contoso. Show that the new session's scope cannot reminder.start, that the previous session id no longer loads, and that a Northwind enrollment id is not_found under the Contoso principal.

    Deliverable and Rubric

    Submit the diagram, the source with no secrets, the test output, the six-row control table, and a short note on why a JWT role claim is the wrong revocation story for the browser.

    AreaWeight
    Conceptual accuracy and architecture20%
    Working implementation and code quality25%
    Security, privacy, and responsible AI20%
    Testing, reliability, and observability20%
    Documentation and decision rationale15%

    Production checklist:

    • Sign-in does not accept a role.
    • Session ids rotate on login and on organization switch.
    • Membership is loaded per request.
    • The matrix matches the capstone roles.
    • Learners cannot start or approve reminders.
    • Cross-tenant enrollment reads are not_found.
    • CSRF is required on writes.
    • Cookie flags are set in the composition root.
    • Logs and prompts omit cookies and passwords.
    • Failed authorization does not call the model.

    Key Takeaways

    1. Authentication produces a user id. Authorization reads membership.
    2. The browser session is an opaque server row.
    3. The cookie is HttpOnly, Secure, and SameSite=Lax.
    4. Role and organization come from memberships.
    5. Body role fields are ignored.
    6. Revocation is visible on the next request.
    7. Actions are a versioned matrix.
    8. Learners get object checks, not only a role check.
    9. CSRF protects cookie-authenticated writes.
    10. Organization switch rotates the session and checks membership.
    11. WorkflowScope is built from the principal.
    12. Partner JWTs are short-lived, audience-pinned, and still backed by membership on writes.
    13. Sign-in failures do not enumerate mailboxes.
    14. Secrets stay in ports and out of prompts.
    15. Lesson 47's orchestrator does not change. Its inputs do.

    Summary

    Lesson 48 opens Full-Stack Security, Testing and Deployment by making identity a server fact. TechLearningPro signs a person in, stores an opaque session, and loads memberships before any reminder, enrollment read, or model call. The capstone's WorkflowScope now has a source. A forged role, a revoked instructor, and a cross-tenant id fail in tests you can run without an identity provider. The next lesson makes the organization on that principal the isolation key for every store, not only for this matrix.

    Next Lesson Preview

    Multi-Tenant SaaS Architecture and Data Isolation takes organizationId from this principal and forces it into SQL, caches, object keys, jobs, and model context. You will see why a shared database can still isolate Northwind from Contoso, and which isolation shapes you leave for later regulated customers.

    Further Reading

    Ready to mark this lesson complete?Track your journey across the entire course.