Welcome to Authentication, Authorization, and Ticket Workflows! Your API already has a strong request pipeline: Zod validates and normalizes input, request context assigns trace IDs, JSON guards enforce media types, and custom errors flow into one centralized Express error handler.
In this lesson, you’ll add authenticated user context. A Bearer token will identify a persisted user, and protected mutation routes will derive ticket ownership and comment authorship from that authenticated user rather than trusting IDs supplied in JSON bodies.
You’ll also define the application’s three user roles—customer, agent, and admin. This lesson establishes who the current user is and makes their role available to later middleware. It does not yet restrict actions by role; those authorization rules arrive in the next unit.
Authentication and Authorization
Authentication and authorization answer different questions:
text
Authentication: Who is making this request?Authorization: Is that user allowed to perform this action?
This lesson implements authentication. A valid token resolves to a user containing an ID and role, and that user is stored in the request context.
At this stage:
Any valid authenticated user can create a ticket.
Any valid authenticated user can add a comment.
Any valid authenticated user can patch or delete a ticket.
Read routes remain public.
Role-specific restrictions are not enforced yet.
The user’s role is still important because it prepares the API for later rules such as allowing only agents and administrators to assign tickets or change workflow state.
Defining the Available Roles
The persisted user model lives in src/domain/user.ts. The role values begin with one fixed tuple.
TypeScript
export const userRoles = ["customer", "agent", "admin"] as const;export type UserRole = (typeof userRoles)[number];
userRoles contains the only roles recognized by the application: "customer", "agent", and "admin". These values match the roles stored by the seeded PostgreSQL users.
as const preserves each item as a string literal rather than widening the array to string[].
UserRole is derived from the tuple, producing the union "customer" | "agent" | "admin". The allowed role values are therefore declared once and reused by TypeScript.
Deriving the type prevents the runtime list and compile-time union from drifting apart. When role-based middleware is introduced, it can work with the same UserRole contract.
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal
Modeling a Persisted User
The same file defines the user object returned by repository lookups.
id uniquely identifies the persisted user. Ticket requester IDs and comment author IDs ultimately reference this value.
name contains the user’s display name, while role determines which authorization policies can later apply.
token is the deterministic credential stored for this learning environment. It allows the repository to resolve a Bearer token directly to one user.
createdAt is an ISO-formatted timestamp exposed by the repository model rather than a raw PostgreSQL Date.
The user object is placed in response.locals.user for internal request handling. The routes in this lesson do not return the complete user—including its token—to API clients.
Keeping Learning Tokens in Perspective
The seeded tokens used in this course are plaintext fixtures designed to make API behavior predictable. For example:
customer-token-1
A production authentication system would require additional credential architecture, potentially including hashing, expiration, rotation, revocation, sessions or JWTs, and OAuth or OpenID Connect integration. Those concerns are intentionally outside this course.
The important pattern here is the request flow:
Bearer token ↓Parameterized user lookup ↓Authenticated User ↓response.locals.user ↓Protected route handler
Representing PostgreSQL User Rows
The repository in src/repositories/user-repository.ts defines the database-facing row shape.
Keeping userExists() avoids breaking code that may still import it while authentication is introduced incrementally. Production creation routes no longer need it for requester or author body fields because those fields are being removed.
Understanding Bearer Authentication
Protected requests use the HTTP Authorization header:
The middleware parses the scheme and credential separately. The scheme comparison is case-insensitive, so both Bearer and bearer are accepted, but a missing or empty credential is still rejected before the database lookup begins.
A correctly shaped Bearer header can still contain an invalid token. The middleware distinguishes these two failure categories so clients receive a more accurate message.
Authenticating a Request
The authentication middleware lives in src/middleware/authenticate.ts.
export const authenticate: RequestHandler = async ( request, response, next,) => { const authorization = request.header("authorization"); if (!authorization?.startsWith("Bearer ")) { next( new AppError( 401, "UNAUTHORIZED", "A Bearer token is required.", ), ); return; }
request.header("authorization") reads the incoming header using Express’s case-insensitive header API.
startsWith("Bearer ") requires the expected scheme and spacing.
A missing or malformed header becomes a 401 UNAUTHORIZEDAppError.
The middleware delegates through next(error) instead of formatting the response itself. The centralized error handler adds the standard error shape and request metadata.
Once the scheme is accepted, the token is extracted and normalized.
trim() removes accidental whitespace around the credential.
findUserByToken() performs the parameterized PostgreSQL lookup.
An unknown token produces a separate authentication error.
if (!user) { next( new AppError( 401, "UNAUTHORIZED", "The supplied token is invalid.", ), ); return;}
The request had the correct Bearer format, but no persisted user matched the token.
The response still uses 401, but its message distinguishes the invalid credential from a missing Bearer header.
A successful lookup establishes the user context.
response.locals.user = user;next();
The authenticated User is stored in response.locals, which is scoped to the current request.
Later middleware and handlers can read the same user without parsing or querying the token again.
next() is called exactly once after successful authentication.
Reading the Current User Safely
Protected handlers use getCurrentUser() instead of directly casting response.locals.user each time.
export function getCurrentUser( response: Response,): User { const user = response.locals.user as User | undefined; if (!user) { throw new AppError( 500, "AUTH_CONTEXT_MISSING", "Authenticated user context is missing.", ); } return user;}
When authenticate has run successfully, the helper returns the stored user with a precise User type.
If a handler calls the helper without first mounting authentication, the helper does not silently return undefined.
AUTH_CONTEXT_MISSING is a server error because it indicates incorrect route composition rather than invalid client credentials.
This defensive check makes mistakes in middleware ordering visible during development.
Removing Client-Controlled Ticket Ownership
In the previous course, ticket creation accepted requesterId in the JSON body:
That design allowed the client to claim any existing user as the requester. An existence check protected database integrity, but it did not prove identity.
The updated schema in src/schemas/ticket-schemas.ts removes that field.
export const createTicketBodySchema = z.object({ title: z.string().trim().min(3).max(120), description: z .string() .trim() .max(1000) .default(""), priority: z .enum(ticketPriorities) .default("medium"),});
The client now supplies only ticket content and priority.
Title, description, and priority validation remain unchanged.
requesterId is no longer accepted or required by the request schema.
The server derives ownership from the authenticated user.
The repository’s CreateTicketInput still includes requesterId because PostgreSQL needs an owner for the inserted ticket. The difference is that the route now fills that property from trusted request context.
Removing Client-Controlled Comment Authorship
Comment creation follows the same principle.
The earlier body shape included:
{ "authorId": "usr_agent_1", "message": "A comment"}
Message trimming and length validation remain unchanged.
authorId is no longer part of client-controlled JSON.
The nested route obtains the author ID from getCurrentUser().
This change removes the need for route-level userExists() checks for requester and author IDs. Authentication has already resolved the token to a real persisted user.
Protecting Ticket Creation
The collection route in src/routes/ticket-routes.ts applies authentication only to POST.
A valid Bearer token is now required before the update proceeds.
The ticket ID and body continue through the shared Zod pipeline.
The repository and missing-ticket behavior remain unchanged.
The current user is authenticated but not yet authorized against the target ticket.
At this stage, a customer token can still patch a ticket belonging to another user. Authentication establishes identity; the next unit introduces ownership and role restrictions.
Protecting Ticket Deletion
Deletion also requires a valid authenticated user.
.delete( authenticate, validateRequest({ params: ticketIdParamsSchema, }), async (_request, response) => { const { params } = response.locals.validated as { params: TicketIdParams; }; if (!(await deleteTicket(params.ticketId))) { throw new AppError( 404, "TICKET_NOT_FOUND", "Ticket not found.", ); } response.status(204).send(); },)
DELETE has no JSON body, so it does not use requireJson.
Authentication runs before the parameter validator and repository mutation.
Successful deletion still returns 204 No Content.
Any authenticated role may delete in this unit. Administrator-only deletion is an authorization concern introduced later.
Creating Comments as the Authenticated User
The nested comment GET remains public, while POST requires authentication.
The parent ticket router has already validated ticketId and confirmed that the parent exists.
authenticate resolves the comment author.
Zod validates only the message body.
createComment() receives user.id as the author ID.
A request body now looks like:
{ "message": "The authenticated user becomes the author."}
There is no authorId field for the client to choose.
Keeping Read Routes Public
This unit applies authentication narrowly to mutation handlers.
The following routes remain public:
GET /api/ticketsGET /api/tickets/statsGET /api/tickets/:ticketIdGET /api/tickets/:ticketId/comments
The following routes require a valid Bearer token:
POST /api/ticketsPATCH /api/tickets/:ticketIdDELETE /api/tickets/:ticketIdPOST /api/tickets/:ticketId/comments
Router-wide authentication is intentionally deferred until authorization rules are added. This lets the API introduce identity without changing the existing public read behavior all at once.
Using the Authorization Tab
The API Simulator provides an Authorization tab for adding credentials without manually constructing the header.
Keep the base URL set to:
http://localhost:4000
To authenticate a request:
Open the Authorization tab.
Select Bearer Token as the authentication type.
Enter customer-token-1 in the token field.
Configure the request method, path, and JSON body.
Send the request.
The simulator adds the equivalent HTTP header:
Authorization: Bearer customer-token-1
The token field may appear masked in the interface, but the configured value is sent with the request.
Creating an Authenticated Ticket
First, try the protected route without any Authorization configuration:
POST /api/tickets
Use this JSON body:
{ "title": "Authenticated creation check", "description": "Identity comes from the token.", "priority": "high"}
The request should return:
401 UNAUTHORIZED
The error explains that a Bearer token is required.
Now open the Authorization tab, select Bearer Token, and enter:
customer-token-1
Send the same request again. It should return 201 Created with a ticket similar to:
{ "id": "tkt_00c92773-d2c4-42d6-917c-9fe4847ee0d4", "title": "Authenticated creation check", "description": "Identity comes from the token.", "status": "open", "priority": "high", "requesterId": "usr_customer_1", "assigneeId": null, "createdAt": "2026-07-23T10:18:44.973Z", "updatedAt": "2026-07-23T10:18:44.973Z"}
Notice that the body did not contain requesterId, but the stored ticket does. The server derived it from the authenticated user.
Distinguishing Authentication Failures
A missing or malformed scheme produces:
{ "error": { "code": "UNAUTHORIZED", "message": "A Bearer token is required." }, "meta": { "requestId": "generated-or-preserved-id", "durationMs": 1 }}
A correctly formatted but unknown token produces a different message:
Authorization: Bearer not-a-real-token
{ "error": { "code": "UNAUTHORIZED", "message": "The supplied token is invalid." }, "meta": { "requestId": "generated-or-preserved-id", "durationMs": 2 }}
Both use HTTP 401, but the middleware distinguishes a missing authentication scheme from an invalid credential.
Testing Authenticated Comments
Create or choose an existing ticket, then send:
POST /api/tickets/<ticket-id>/comments
With Bearer token:
customer-token-1
And JSON body:
{ "message": "Created by the authenticated customer."}
The returned comment should contain:
{ "authorId": "usr_customer_1"}
Again, the body contains no author ID. The server obtains it from response.locals.user.
Remove the Authorization configuration and resend the request. The route should return 401 UNAUTHORIZED before the comment repository runs.
Testing the Protected Update and Delete Routes
Copy the ID of a disposable ticket and send:
PATCH /api/tickets/<ticket-id>
With a valid Bearer token and JSON body:
{ "status": "in_progress", "priority": "high"}
The request should succeed because any authenticated role may update tickets in this unit.
Then try the same request without a token. It should return 401.
Deletion follows the same identity rule:
DELETE /api/tickets/<ticket-id>
Valid token: deletion may proceed.
Missing token: 401 UNAUTHORIZED.
Invalid token: 401 UNAUTHORIZED.
Do not include a body or content type for DELETE; only authentication and the route parameter are required.
Authentication Does Not Yet Mean Permission
After authentication, the API knows the user’s identity and role:
That does not automatically mean the user should be allowed to perform every protected action.
For example, the middleware currently confirms:
This request comes from usr_customer_1.
It does not yet decide:
May a customer delete this ticket?May an agent edit a customer-owned ticket?May only an admin perform this action?
Those are authorization questions. The role is now available in response.locals.user, so later middleware can answer them without looking up the user again.
Completing an Authenticated Lifecycle
Use customer-token-1 in the Authorization tab and complete this flow:
POST /api/ticketsGET /api/tickets/<new-id>PATCH /api/tickets/<new-id>POST /api/tickets/<new-id>/commentsGET /api/tickets/<new-id>/commentsDELETE /api/tickets/<new-id>
The mutation bodies should not include requesterId or authorId.
Ticket creation:
{ "title": "Authenticated lifecycle check", "description": "Requester comes from the Bearer token.", "priority": "medium"}
Ticket update:
{ "status": "in_progress"}
Comment creation:
{ "message": "Authorship also comes from the Bearer token."}
The ticket’s requesterId and the comment’s authorId should both be usr_customer_1.
Recap
You’ve introduced the persisted user and role model that supports authentication and future authorization. userRoles defines the supported customer, agent, and admin roles, while UserRole derives its TypeScript union from the same tuple.
The user repository now performs parameterized lookups by token and ID and maps PostgreSQL rows into consistent application users. authenticate distinguishes missing Bearer credentials from invalid tokens, stores valid users in response.locals.user, and delegates failures into the centralized error pipeline.
Most importantly, ticket requester IDs and comment author IDs no longer come from client-controlled JSON. Protected routes call getCurrentUser() and derive ownership from the authenticated user. Read routes remain public, while creation, updates, deletion, and comment creation require a valid Bearer token.
The API now knows who is making each protected request. In the next unit, it can begin deciding what customers, agents, and administrators are allowed to do.
if (!user) { next( new AppError( 401, "UNAUTHORIZED", "The supplied token is invalid.", ), ); return;}
TypeScript
response.locals.user = user;next();
TypeScript
export function getCurrentUser( response: Response,): User { const user = response.locals.user as User | undefined; if (!user) { throw new AppError( 500, "AUTH_CONTEXT_MISSING", "Authenticated user context is missing.", ); } return user;}