Authentication and Authorization Errors
You'll learn how to present 401 and 403 errors in a way that's helpful to users without exposing your application's security mechanisms.
The Communication Challenge
When authentication or authorization fails, you're walking a tightrope: you need to help legitimate users understand what went wrong, but you don't want to give attackers clues about your security setup. Revealing details like "invalid username" vs "invalid password" tells attackers which part of their attempt was correct.
What to Show Users
For 401 (Unauthorized) errors:
- Generic message: "Your session has expired. Please log in again."
- Avoid: "Invalid token signature" or "Token expired at 14:32:01"
- Provide a clear path: redirect to login or show a login button
For 403 (Forbidden) errors:
- Simple explanation: "You don't have permission to access this resource."
- Avoid: "Missing admin role" or "Insufficient scope: write:posts"
- Don't hint at why — just that access is denied
The Security Balance
Think of it like a bouncer at a club: they say "Sorry, you can't come in" — not "Your ID is fake" or "You need to know the owner." The less specific you are, the less information potential attackers can use.
// Good: Vague but helpful
"Access denied. Please contact support if you believe this is an error."
// Bad: Too revealing
"Access denied. Required permission: admin.delete.users"
Your error messages should acknowledge the problem, guide users toward a solution (re-login, contact support), but never explain your authorization logic or token structure.
Key Takeaway: Present authentication and authorization errors with generic, user-friendly messages that help legitimate users without revealing security implementation details to potential attackers.