Bearer middleware and request context
You can verify a bearer token once and pass the authenticated caller through the request context so GET /v1/me can retrieve the correct account.
Learning outcomes
- Explain how HTTP middleware wraps handlers and how chi executes middleware in registration order.
- Verify bearer tokens using the existing JWT signer and return one consistent authentication error for invalid credentials.
- Pass the verified caller through a typed request context value using a private key.
- Use the authenticated caller's identity to retrieve current account details from MySQL while keeping public routes accessible.
A client that signs in receives an access token. When it requests GET /v1/me, your API must verify that token before the handler reads the caller's account from MySQL. A missing or invalid token must stop the request before the handler executes.
You could repeat token extraction and verification inside every protected handler. That would duplicate security logic and make it easy for one endpoint to behave differently from another. Your Go API already has a mechanism for applying shared request logic before handlers run.
Request processing with middleware
HTTP middleware wraps an existing HTTP handler. It can inspect an incoming request, reject it, or prepare information before passing it to the next handler.
In Go, an HTTP handler implements http.Handler:
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}A middleware accepts one handler and returns another:
func(http.Handler) http.HandlerThe returned handler controls when the original handler executes. This allows middleware to perform work before and after the application handler.
For example, several middleware layers can process the same request:
- RequestID adds a request identifier.
- Logger records request information.
- RateLimit checks the request against the configured limit.
- Authentication middleware verifies the bearer token when the route requires it.
- The final handler processes the request.
Each layer can stop processing by writing a response and returning without calling the next handler.
Middleware execution order in chi
Your backend uses chi v5. The root router already registers middleware using Use:
router.Use(middleware.RequestID)
router.Use(middleware.Logger)
router.Use(httpx.RateLimit(limiter))Chi runs these middleware in registration order. The first registered middleware is the outermost layer.
This means the request passes through RequestID first, then Logger, then RateLimit. A protected route can add authentication middleware after these global layers.
The response travels back through the wrapping layers after the inner handler finishes. This is useful for logging the final response or recording request duration.
Public and protected routes
Not every endpoint should require a bearer token.
Your API has public endpoints that clients must access before they are authenticated:
POST /v1/auth/signupPOST /v1/auth/loginPOST /v1/auth/refreshGET /healthz- Week 2 restaurant routes, including
GET /v1/restaurants
The GET /v1/me endpoint requires an authenticated caller. Later order endpoints will have the same requirement.
Chi supports route groups with their own middleware. You can register public routes on the root router and place protected routes inside a separate group.
router.Get("/v1/restaurants", restaurants.List)
router.Group(func(r chi.Router) {
r.Use(signer.Middleware)
// Register protected endpoints here.
})The authentication middleware applies only to routes registered inside that group.
This makes the router structure communicate which endpoints require authentication.


A rejected request never reaches the final handler. This is important because the handler should not need to repeat the authentication checks.
Bearer token extraction
A protected request sends its access token through the HTTP Authorization header.
GET /v1/me
Authorization: Bearer <access_token>The word Bearer identifies the authentication scheme. The value following the required space is the credential.
Your middleware must reject malformed headers instead of trying to interpret every Authorization value as a token.
Go provides strings.CutPrefix for extracting the exact prefix:
raw, ok := strings.CutPrefix(
r.Header.Get("Authorization"),
"Bearer ",
)The result contains the remaining string. The boolean reports whether the prefix was found.
Consider these inputs:
| Authorization value | Prefix found | Token |
|---|---|---|
Bearer abc123 | Yes | abc123 |
Basic abc123 | No | Empty |
| Empty header | No | Empty |
Bearer | Yes | Empty |
Bearerabc123 | No | Empty |
You must check both the prefix result and whether the extracted token is empty.
An empty token is not a valid credential. A Basic authorization header is also not accepted by this endpoint.
After extraction, the middleware delegates verification to the existing signer from the JWT lesson.
JWT verification at the HTTP boundary
The earlier JWT lesson introduced the signer and its parsing behaviour. The middleware should reuse that verification logic rather than implementing cryptographic checks itself.
The access token must be a valid, unexpired JWT signed with HS256 using JWT_SECRET.
The signer rejects tokens with an invalid signature, expired claims or an unexpected signing algorithm. The parser must accept only HS256.
Consider the credentials exercised by the W3B2 tests:
| Credential | Expected result |
|---|---|
| Basic authorization scheme | HTTP 401 |
| Empty Bearer value | HTTP 401 |
Bearer not-a-jwt | HTTP 401 |
| Bearer without the required space | HTTP 401 |
| Expired HS256 token | HTTP 401 |
| Token signed with HS384 | HTTP 401 |
Token with alg: none | HTTP 401 |
| Token signed with another secret | HTTP 401 |
| Token with an edited payload | HTTP 401 |
| Refresh token used as a bearer token | HTTP 401 |
The edited-payload case is particularly important. A client can decode the JWT and change its customer role claim to restaurant, but it cannot produce a valid replacement signature without the signing secret.
The tests also use the incorrect signing secret an-attacker-secret-that-is-32-bytes!. A token signed with that value must not be accepted by an API configured with its own JWT_SECRET.
A refresh token must also fail. It is an opaque credential stored in Redis, not a signed JWT.
One authentication failure response
All tested authentication failures return HTTP 401 with the same error code:
{
"error": "unauthorized"
}Do not expose whether the token was expired, malformed or signed with the wrong secret.
The client only needs to know that the supplied bearer token was not accepted. Consistent failures also prevent the API from revealing unnecessary details about its authentication checks.
Passing the caller through context
Once the signer verifies an access token, it can identify the authenticated account.
The signer returns a Principal containing the account's user ID and role:
type Principal struct {
UserID int64
Role string
}The middleware needs to pass this principal to the next handler.
A client-controlled HTTP header is not the right place for trusted internal identity. Instead, use Go's request context.
A context value carries request-scoped information across function boundaries without adding another explicit argument to every function.
ctx := context.WithValue(
r.Context(),
key,
principal,
)The next handler can retrieve the principal from the derived context.
This is a good fit for authentication because the caller's identity belongs to the lifetime of the current request.
Private context keys
Avoid using ordinary string keys such as "user" or "principal".
context.WithValue(ctx, "user", principal)Another package could independently choose the same string key for a different value. This creates a risk of collisions.
Use an unexported package-specific key type instead:
type ctxKey struct{}The type remains private to the auth package. Other packages cannot directly refer to that exact type.
A zero-sized struct is also suitable as a key because it carries no additional data.
A typed accessor
You do not want every handler to know the internal context key or repeat a type assertion.
Keep that operation inside one accessor:
func From(ctx context.Context) (Principal, bool) {
p, ok := ctx.Value(ctxKey{}).(Principal)
return p, ok
}A handler can now retrieve the caller through the package's public API:
principal, ok := auth.From(r.Context())
if !ok {
// Handle a missing principal.
}The boolean matters. A handler might be called directly in a test without authentication middleware, or another route might invoke it without establishing a principal.
Returning false lets the handler handle that case without panicking.
Context derivation and request copying
Go contexts are immutable. Calling context.WithValue does not modify the original context.
It returns a new context that contains the value and refers to the original context as its parent.
Similarly, r.WithContext(ctx) returns a shallow copy of the HTTP request with the new context attached.
This distinction matters in middleware. Creating a new context is not enough. You must pass the request containing that context to the next handler.
ctx := context.WithValue(r.Context(), key, principal)
next.ServeHTTP(w, r.WithContext(ctx))If you pass the original request instead, the downstream handler will not see the principal.
Context values and request lifetime
Context values are intended for request-scoped information that needs to cross function boundaries.
Common examples include:
- The authenticated caller.
- A request ID.
- A tracing identifier.
Contexts also carry cancellation signals and deadlines. For example, your GET /v1/me database query can derive a timeout from the incoming request context.
Do not use context as a general-purpose dependency container.
Database handles, Redis clients and application configuration belong in explicit dependencies. Ordinary function arguments should remain function arguments.
A useful distinction is whether the information belongs to the current request and needs to travel through several layers. If it does not, context is probably not the right place for it.
Account data from MySQL
A verified principal establishes who the caller is. It does not replace the current account record in MySQL.
The GET /v1/me handler uses the principal's user ID to retrieve the account from users.
The account response contains:
| Field | Source |
|---|---|
id | users.id |
email | users.email |
role | users.role |
restaurant_id | users.restaurant_id |
For example, a customer response looks like:
{
"id": 7,
"email": "customer@example.test",
"role": "customer",
"restaurant_id": null
}A restaurant account registered with restaurant_id set to 3 should return that value.
Notice the explicit null for a customer. Omitting restaurant_id would not satisfy the account response contract.
Using MySQL as the source of account details also avoids relying on token claims for information that may have changed since token issuance.
The principal supplies the identity used for the lookup. The database supplies the current email, role and restaurant association.
Authentication and authorization remain separate responsibilities. Verification establishes the caller. Later order handlers can use the caller's role to decide whether a particular operation is allowed.
Middleware and protected account requests
The exercise GET /v1/me: caller account brings these pieces together.
The authentication middleware extracts the bearer token and delegates its validation to the signer. It must reject every invalid credential with HTTP 401 and unauthorized before the handler runs.
For a valid token, the middleware makes the verified principal available through the request context. The account handler uses that principal's ID to retrieve the current record from MySQL.
Keep the route groups separate. /v1/me requires authentication, while /healthz, /v1/auth/* and Week 2 restaurant routes remain public.
The same authentication context will support order ownership and role checks in later exercises. Establishing the caller once at the request boundary means those handlers can focus on their own business rules.
Check your understanding
A request to GET /v1/me contains a valid JWT signed with HS256, but the payload has been changed from customer to restaurant without generating a new signature. What should happen?
References
Everything above is explained on this page; these are where it comes from (Go 1.25 net/http, go-chi/chi v5).