Contracts and security
Place the authentication boundary
Separate identifying a caller from deciding whether that caller may perform one specific operation.
8 minute lesson
Authentication answers who is calling. Authorization answers whether that identity may access this book or operation.
Put authentication in middleware that produces a trusted identity, then enforce ownership or roles close to the resource query. Never accept a user ID from the request body as proof of identity. The later Web Authentication course builds the complete mechanism.
Middleware should either reject the request or attach a small trusted principal such as an internal user ID and roles. Handlers consume that principal; they do not reparse credentials or trust ownership fields from JSON. Keep the raw token out of logs and application objects.
Authorization belongs in the data operation. Query or update the book with both its ID and owner ID so another request cannot change ownership between a separate check and write. Use 401 when valid authentication is required and absent or invalid, 403 when an identified caller is forbidden, and optionally 404 when revealing that another user’s resource exists would leak information. Test two users against the same book, not only the owner path.
Add a temporary test identity middleware and restrict updates to books whose owner ID matches it.
Lesson completed