Forbidden error variant
Learn how to add a Forbidden variant to AppError that answers authenticated but not allowed requests with status 403 and how it differs from 401
A request can pass the identity check and still be turned away. A signed-in user who asks for the admin report is known to the server, and the server still says no, because knowing who someone is does not mean they may do everything. That refusal is status 403 Forbidden, and this page adds the variant that produces it.
Where This Fits
The Unauthorized variant covered the front door, the question of who is asking. This page covers the room inside, the question of what a known user may do. Both variants live in the same enum, both use the same JSON shape, and both are returned through the same HandlerResult shorthand. The only difference is the question each one answers.
Think of a company office. The badge reader at the entrance checks whether you work here. That is the 401 check. The locked door to the server room checks whether your badge opens that particular door. You work here, your badge is real, and the door still stays shut, because your job does not include the server room. That is the 403 answer.
The Smallest Working Version
Adding the variant takes the same three edits as the previous one. A new line in the enum, a new message, and a new arm in the status mapping.
use axum::{
Json,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde_json::json;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum AppError {
#[error("resource not found")]
NotFound,
#[error("{0}")]
ValidationError(String),
#[error("something went wrong")]
InternalError,
#[error("unauthorized")]
Unauthorized,
#[error("forbidden")]
Forbidden,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let status = match &self {
AppError::NotFound => StatusCode::NOT_FOUND,
AppError::ValidationError(_) => StatusCode::UNPROCESSABLE_ENTITY,
AppError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
AppError::Unauthorized => StatusCode::UNAUTHORIZED,
AppError::Forbidden => StatusCode::FORBIDDEN,
};
let body = Json(json!({ "error": self.to_string() }));
(status, body).into_response()
}
}
impl From<std::io::Error> for AppError {
fn from(error: std::io::Error) -> Self {
eprintln!("io error: {error}");
AppError::InternalError
}
}
impl From<serde_json::Error> for AppError {
fn from(error: serde_json::Error) -> Self {
eprintln!("json error: {error}");
AppError::InternalError
}
}
pub type HandlerResult<T> = Result<T, AppError>;
The variant carries no data, like the unauthorized one. The message is the single word forbidden, and the status arm maps it to StatusCode::FORBIDDEN, the constant for 403. The body construction is shared, so a forbidden response looks exactly like an unauthorized one apart from the status code and the word inside it.
The handler on this page needs to know more than whether a token is present. It needs to know which role the token belongs to. A role is a named set of permissions, such as admin or ordinary user, that decides what the holder may do. The demo below uses two tokens, one for each role, so the difference between the two checks is visible in a single route.
pub mod errors;
use axum::{
Json, Router,
http::{HeaderMap, header},
routing::get,
};
use errors::{AppError, HandlerResult};
use serde_json::json;
pub fn app() -> Router {
Router::new().route("/admin/report", get(admin_report))
}
async fn admin_report(headers: HeaderMap) -> HandlerResult<Json<serde_json::Value>> {
require_admin(&headers)?;
Ok(Json(json!({ "report": "weekly totals", "signups": 42 })))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Role {
Admin,
User,
}
fn bearer_token(headers: &HeaderMap) -> Option<&str> {
headers
.get(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.strip_prefix("Bearer "))
}
fn role_from_headers(headers: &HeaderMap) -> HandlerResult<Role> {
match bearer_token(headers) {
Some("admin-token") => Ok(Role::Admin),
Some("user-token") => Ok(Role::User),
_ => Err(AppError::Unauthorized),
}
}
fn require_admin(headers: &HeaderMap) -> HandlerResult<()> {
match role_from_headers(headers)? {
Role::Admin => Ok(()),
Role::User => Err(AppError::Forbidden),
}
}
The handler is two lines again. It calls the admin check, and on success returns the report. The check itself is layered. bearer_token pulls the token out of the headers, exactly as on the previous idea. role_from_headers turns a token into a role, and returns the unauthorized variant for anything it does not recognise. require_admin takes that role and returns success for an admin, the forbidden variant for an ordinary user.
use axum_project::app;
#[tokio::main]
async fn main() {
let app = app();
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The entry point is unchanged. A new variant touches the error file and the handlers that use it, never the startup code.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
thiserror = "2.0"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
Three requests show the three outcomes. No token at all is an identity failure.
curl http://127.0.0.1:3000/admin/report
{"error":"unauthorized"}
An ordinary user token passes the identity check and fails the permission check.
curl -H "Authorization: Bearer user-token" http://127.0.0.1:3000/admin/report
{"error":"forbidden"}
An admin token passes both checks and gets the report.
curl -H "Authorization: Bearer admin-token" http://127.0.0.1:3000/admin/report
{"report":"weekly totals","signups":42}
The first two bodies look alike, one word inside a shared shape. The status codes tell them apart, 401 for the first and 403 for the second. A client that reads the status knows whether to log in again or to stop asking.
Working Setup:
If no token gives 401, the ordinary user token gives 403, and the admin token gives 200 with the report, the variant is wired up correctly. The three outcomes come from two layered checks and two variants.
What 403 Means in Plain Words
Status 403 means the server knows who is asking and refuses anyway. The request was understood, the credentials were accepted, and the answer is still no. The user is authenticated, which means their identity was proven, but not authorized, which means they lack permission for this particular action. Authentication and authorization are two different words for two different questions, and 403 is the answer to the second one.
The practical consequence is the opposite of the 401 case. A 403 answer is not an invitation to try again. The same user, logging in again, gets the same refusal, because the refusal is about what the user may do, not about whether the server knows them. The only thing that changes the answer is a different user, or a change to what the user is allowed to do. A client that receives 403 should show the user a message about permission, not a login screen.
The variant carries no data, for the same reason the unauthorized variant carries none. A body that says "you need the admin role" tells an attacker which role to aim for. The single word forbidden says the request was refused and nothing else.
401 and 403 Side by Side
The two statuses are easy to confuse because both say no, and the difference only shows up when the request is examined closely. The table below puts the questions, the causes, and the right client reaction next to each other.
| 401 Unauthorized | 403 Forbidden | |
|---|---|---|
| Question asked | Who is asking? | May this user do this? |
| State of the request | No usable identity | Identity known, permission missing |
| Cause | Missing, expired, or wrong credentials | Authenticated user lacks the needed role |
| Logging in again helps | Yes, with valid credentials | No, the same user gets the same answer |
| What changes the answer | Valid credentials | A different user, or a permission change |
The retry test from the previous idea decides between them in one sentence. If logging in again could fix the request, the answer is 401. If logging in again changes nothing, the answer is 403. Every example below follows that test.
A request with no token at all gets 401, because there is nothing to check permission against. A request with a token for an ordinary user, asking for the admin report, gets 403, because the user is known and the rule is about the role. A request with an admin token asking for a note that does not exist gets 404, because permission passed and the data is missing. A request with an ordinary user token asking to delete another user's note gets 403, because the user may manage their own notes but not someone else's.
The Status Name Is Misleading in the Other Direction Too:
The name Forbidden sounds absolute, as if the resource can never be reached by anyone. It is not absolute. It means forbidden for this user, right now. An admin reaching the same route gets the report without trouble. The refusal belongs to the user, not to the resource.
The Layered Check, Piece by Piece
The three functions form a chain, and each link answers one question. Splitting them keeps each function short enough to read at a glance, and it lets other handlers reuse the middle link. A route that any signed-in user may reach calls role_from_headers directly. A route that only admins may reach calls require_admin.
fn role_from_headers(headers: &HeaderMap) -> HandlerResult<Role> {
match bearer_token(headers) {
Some("admin-token") => Ok(Role::Admin),
Some("user-token") => Ok(Role::User),
_ => Err(AppError::Unauthorized),
}
}
fn require_admin(headers: &HeaderMap) -> HandlerResult<()> {
match role_from_headers(headers)? {
Role::Admin => Ok(()),
Role::User => Err(AppError::Forbidden),
}
}
role_from_headers maps each known token to its role. The catch-all arm returns the unauthorized variant, which is correct, because an unknown token means the identity is not established, and no permission question can be asked yet. require_admin calls that function with ?, which returns early with the unauthorized variant when the token is unknown, and unwraps the role when it is known. The match then sorts the known roles. Admin passes. Ordinary user fails with the forbidden variant.
The Role enum is small on purpose. Two variants, admin and user, cover the demo. The derive list on it, Debug, Clone, Copy, PartialEq, Eq, gives it the usual conveniences. Copy matters here, because the role is matched by value and a copyable enum can be used without moving it. A real application would load roles from a database or a token claim, which is a piece of data inside the token that states what the holder may do, instead of matching hard-coded strings. The shape of the check stays the same either way. Identity first, role second, decision third.
Never Hard Code Roles in a Real Application:
The tokens admin-token and user-token are teaching stand-ins, like the token on the previous idea. A real application verifies the token against a session store or an identity service and reads the role from the stored session or the token itself. Hard-coded tokens and roles in source code are readable by anyone with the source, and the check is worth nothing once they are known.
Reusing the Check Across Routes
The admin check is not tied to the report route. A delete route needs the same protection, and it calls the same function. The handler below deletes a user by id, returning status 204, which means the request succeeded and there is no body to send back.
use axum::{Json, Router, extract::Path, http::StatusCode, routing::{delete, get}};
pub fn app() -> Router {
Router::new()
.route("/admin/report", get(admin_report))
.route("/admin/users/{id}", delete(delete_user))
}
async fn delete_user(
headers: HeaderMap,
Path(id): Path<u32>,
) -> HandlerResult<StatusCode> {
require_admin(&headers)?;
let _ = id;
Ok(StatusCode::NO_CONTENT)
}
The handler takes two extractor arguments, the header map and the path id. The admin check runs first, before the id is used for anything. The let _ = id; line marks the id as intentionally unused, because the demo has no database to delete from. In a real handler the id would select the row to delete. The return type is HandlerResult<StatusCode>, a result whose success type is a bare status code, which Axum turns into an empty response with that status.
Requesting the delete route with the ordinary user token gives the same 403 as the report route, which shows the check is shared rather than copied.
curl -X DELETE -H "Authorization: Bearer user-token" http://127.0.0.1:3000/admin/users/7
{"error":"forbidden"}
Requesting it with the admin token gives an empty 204 response, which is the success case for a delete.
curl -i -X DELETE -H "Authorization: Bearer admin-token" http://127.0.0.1:3000/admin/users/7
HTTP/1.1 204 No Content
A Plain Text Diagram of the Flow
The request passes two gates in order, and the failure at each gate has its own status.
request arrives with headers
|
v
role_from_headers: is the token known?
|
+-- no --> AppError::Unauthorized --> 401 + {"error": "unauthorized"}
|
+-- yes, Role::User --> require_admin refuses
| |
| v
| 403 + {"error": "forbidden"}
|
+-- yes, Role::Admin --> handler builds the report
|
v
200 + {"report": "weekly totals", ...}
The order of the gates is the whole design. Identity is checked before permission, because permission has no meaning without an identity to attach it to. A handler that checked permission first would have to answer the question "may this unknown user do this" which has no sensible answer.
Testing It
The tests cover the full matrix, no token, ordinary user token, and admin token, for the report route, plus the delete route to prove the check is shared. Each test sends a request through the router with oneshot and checks the status and the exact body.
use axum::{
body::{Body, to_bytes},
http::{Method, Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;
async fn body_text(response: axum::response::Response) -> String {
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
String::from_utf8(bytes.to_vec()).unwrap()
}
async fn call(uri: &str, method: Method, token: Option<&str>) -> (StatusCode, String) {
let mut builder = Request::builder().uri(uri).method(method);
if let Some(token) = token {
builder = builder.header("authorization", format!("Bearer {token}"));
}
let response = app()
.oneshot(builder.body(Body::empty()).unwrap())
.await
.unwrap();
let status = response.status();
(status, body_text(response).await)
}
#[tokio::test]
async fn report_without_token_is_unauthorized() {
let (status, body) = call("/admin/report", Method::GET, None).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body, r#"{"error":"unauthorized"}"#);
}
#[tokio::test]
async fn report_with_user_token_is_forbidden() {
let (status, body) = call("/admin/report", Method::GET, Some("user-token")).await;
assert_eq!(status, StatusCode::FORBIDDEN);
assert_eq!(body, r#"{"error":"forbidden"}"#);
}
#[tokio::test]
async fn report_with_admin_token_returns_report() {
let (status, body) = call("/admin/report", Method::GET, Some("admin-token")).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, r#"{"report":"weekly totals","signups":42}"#);
}
#[tokio::test]
async fn delete_with_user_token_is_forbidden() {
let (status, body) = call("/admin/users/7", Method::DELETE, Some("user-token")).await;
assert_eq!(status, StatusCode::FORBIDDEN);
assert_eq!(body, r#"{"error":"forbidden"}"#);
}
#[tokio::test]
async fn delete_with_admin_token_returns_no_content() {
let (status, body) = call("/admin/users/7", Method::DELETE, Some("admin-token")).await;
assert_eq!(status, StatusCode::NO_CONTENT);
assert_eq!(body, "");
}
The shared call helper builds any request with any method and an optional token, so the five tests stay short. The user-token test on the report route is the one that guards the new variant. If somebody later changes the role check to return the unauthorized variant for ordinary users, that test fails on the status code, which forces the change to be a deliberate decision rather than a slip.
Common Beginner Mistakes
Returning 401 for a Known User Without Permission
// Wrong - the user is known, the answer is about permission
fn require_admin(headers: &HeaderMap) -> HandlerResult<()> {
match role_from_headers(headers)? {
Role::Admin => Ok(()),
Role::User => Err(AppError::Unauthorized),
}
}
This is the most common mix-up on this page, and it is the exact mirror of the mistake on the previous idea. The user proved who they are, so a 401 tells the client to log in again, and logging in again changes nothing. The fix is the forbidden variant. When the identity is known and the rule says no, the answer is 403.
One Status Per Question:
Each status answers one question. 401 answers identity, 403 answers permission, 404 answers existence, 422 answers input. A handler that returns a status for the wrong question sends the client down the wrong path. Check which question failed before choosing the variant.
Checking Permission Before Identity
// Wrong - there is no user to check permission against
fn require_admin(headers: &HeaderMap) -> HandlerResult<()> {
let role = role_from_headers(headers)?;
match role {
Role::Admin => Ok(()),
Role::User => Err(AppError::Forbidden),
}
}
This version looks almost right, because role_from_headers already returns the unauthorized variant for unknown tokens. The mistake is subtler. The code reads as if permission were checked first, and a future edit that replaces the helper with a direct role lookup would return 403 for a missing token. Keep the two steps visible and in order. Identity first, in its own function, then permission, in its own function. The layering is the guarantee.
Naming the Required Role in the Response
// Wrong - the body tells an attacker which role to aim for
Role::User => Err(AppError::ValidationError("admin role required".to_string())),
Two things are wrong here. The variant is wrong, because a permission refusal is not a validation failure, so the status would be 422 instead of 403. And the message names the required role, which teaches an attacker exactly what to steal or forge. The fix is the forbidden variant with its single generic word.
Checking the Role After Doing the Work
// Wrong - the report is built before the caller is allowed to see it
async fn admin_report(headers: HeaderMap) -> HandlerResult<Json<serde_json::Value>> {
let report = build_report().await?;
require_admin(&headers)?;
Ok(Json(report))
}
Building the report before the check wastes work and risks leaking information through side effects, such as log entries that record that the report was built. The check belongs on the first line of the handler, before any other work, exactly as the working version does it.
Using 403 to Hide a Missing Resource
// Wrong - the resource does not exist, and 403 hides that fact for the wrong reason
async fn get_note(id: u32) -> HandlerResult<Json<serde_json::Value>> {
if id != 1 {
return Err(AppError::Forbidden);
}
Ok(Json(json!({ "id": 1, "title": "First note" })))
}
Some applications do return 404 instead of 403 when a resource is hidden from a user, so that the user cannot tell whether it exists. That is a deliberate design choice, and it uses 404, not 403, as the hiding status. Returning 403 for a resource that simply does not exist confuses the client. It says the user lacks permission for something that is not there at all. A missing resource is a 404, whatever the user may do elsewhere.
Final Complete Example
Here is the full project from this page, with both auth variants, the layered check, and two protected routes.
use axum::{
Json,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde_json::json;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum AppError {
#[error("resource not found")]
NotFound,
#[error("{0}")]
ValidationError(String),
#[error("something went wrong")]
InternalError,
#[error("unauthorized")]
Unauthorized,
#[error("forbidden")]
Forbidden,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let status = match &self {
AppError::NotFound => StatusCode::NOT_FOUND,
AppError::ValidationError(_) => StatusCode::UNPROCESSABLE_ENTITY,
AppError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
AppError::Unauthorized => StatusCode::UNAUTHORIZED,
AppError::Forbidden => StatusCode::FORBIDDEN,
};
let body = Json(json!({ "error": self.to_string() }));
(status, body).into_response()
}
}
impl From<std::io::Error> for AppError {
fn from(error: std::io::Error) -> Self {
eprintln!("io error: {error}");
AppError::InternalError
}
}
impl From<serde_json::Error> for AppError {
fn from(error: serde_json::Error) -> Self {
eprintln!("json error: {error}");
AppError::InternalError
}
}
pub type HandlerResult<T> = Result<T, AppError>;
pub mod errors;
use axum::{
Json, Router,
extract::Path,
http::{HeaderMap, StatusCode, header},
routing::{delete, get},
};
use errors::{AppError, HandlerResult};
use serde_json::json;
pub fn app() -> Router {
Router::new()
.route("/admin/report", get(admin_report))
.route("/admin/users/{id}", delete(delete_user))
}
async fn admin_report(headers: HeaderMap) -> HandlerResult<Json<serde_json::Value>> {
require_admin(&headers)?;
Ok(Json(json!({ "report": "weekly totals", "signups": 42 })))
}
async fn delete_user(
headers: HeaderMap,
Path(id): Path<u32>,
) -> HandlerResult<StatusCode> {
require_admin(&headers)?;
let _ = id;
Ok(StatusCode::NO_CONTENT)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Role {
Admin,
User,
}
fn bearer_token(headers: &HeaderMap) -> Option<&str> {
headers
.get(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.strip_prefix("Bearer "))
}
fn role_from_headers(headers: &HeaderMap) -> HandlerResult<Role> {
match bearer_token(headers) {
Some("admin-token") => Ok(Role::Admin),
Some("user-token") => Ok(Role::User),
_ => Err(AppError::Unauthorized),
}
}
fn require_admin(headers: &HeaderMap) -> HandlerResult<()> {
match role_from_headers(headers)? {
Role::Admin => Ok(()),
Role::User => Err(AppError::Forbidden),
}
}
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
thiserror = "2.0"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
Run the checks with these commands.
cargo check
cargo test
cargo run
Summary
The framework from this page and the previous one together is a two-question test that fits every protected route. First, who is asking? If nobody can be identified, the answer is 401, and the client can fix it by proving its identity. Second, may this user do this? If the user is known and the rule says no, the answer is 403, and no amount of re-logging changes it. Only when both questions pass does the handler do its work.
That order is what keeps the error handling honest. A single check that mixed identity and permission would return one status for two different failures, and the client would never know whether to log in again or to stop asking. Two variants, two layered helpers, and one shared JSON shape give the client exactly the information it needs, and nothing it should not have.