Protected route 401 assertion
Learn how to assert every way a protected route can answer 401, why the status and the body must both be checked, and how 401 differs from 403
A protected route has two jobs: let the right requests in, and keep the wrong ones out with the right answer. The previous page proved the first job. This page proves the second, case by case. A missing token, a garbage token, a token signed with the wrong secret, and an expired token must all answer the same way: status 401, and the body {"error": "unauthorized"}. If any one of them answers differently, the route is leaking information about which check failed, or it is letting a bad request further in than it should go.
Where This Fits
The authenticated-request page built the happy path: mint a token, send it, get 200. This page is the other half of the same contract. A test suite that only checks the happy path can pass while the route accepts garbage, because nothing ever sent garbage. The negative tests here are the proof that the door is actually locked, and they use the same app, the same token helper, and the same request helper as the previous page, so nothing new needs to be built except the assertions.
Think of a bouncer with a list of ways to say no. No pass, a fake pass, a pass from another club, and an expired pass must all get the same answer at the door, or a person probing the door learns which kind of pass the bouncer checks first. The tests below are the probing, done on purpose, before anyone else does it for real.
The Smallest Working Version
The smallest negative test sends no token at all and checks the status and the body. The app is the same auth_app from the previous page, with the login, profile, and admin routes, and the same shared error type, where Unauthorized becomes 401 with the body {"error": "unauthorized"}.
use axum::{Router, body::Body, http::{Request, StatusCode}};
use axum_project::{auth_app, test_state};
use http_body_util::BodyExt;
use serde_json::{Value, json};
use tower::ServiceExt;
async fn get_profile(token: Option<String>) -> (StatusCode, Value) {
let mut builder = Request::builder().uri("/profile");
if let Some(token) = token {
builder = builder.header("authorization", format!("Bearer {token}"));
}
let response = auth_app(test_state().await)
.oneshot(builder.body(Body::empty()).unwrap())
.await
.unwrap();
let status = response.status();
let bytes = response.into_body().collect().await.unwrap().to_bytes();
(status, serde_json::from_slice(&bytes).unwrap())
}
#[tokio::test]
async fn no_token_is_401_with_the_generic_body() {
let (status, body) = get_profile(None).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body, json!({ "error": "unauthorized" }));
}
The helper builds a GET request to /profile, adds the header only when a token is given, and returns the status and the parsed JSON body. The test passes None, so no header is sent, and asserts two things: the status is 401, and the body is exactly {"error": "unauthorized"}. Both assertions matter, and the next section explains why.
Run it with:
cargo test --test auth_401_test
The output ends with the test passing. That one test is the baseline for the whole page. Every other test below follows the same shape, with a different bad token in place of None.
Working Setup:
If the no-token test passes, the extractor is rejecting requests before the handler runs, and the shared error conversion is producing the generic body. If it fails with a 200, the route is not protected at all. If it fails with a 401 but a different body, the error conversion is wrong somewhere.
Why the Body Matters as Much as the Status
A test that asserts only the status can pass while the server leaks information. Consider a login that answers an unknown email with 401 and the body {"error": "no account with that email"}, and a wrong password with 401 and the body {"error": "wrong password"}. Both statuses are 401, so a status-only test passes, and an attacker can still sort real accounts from invented ones by reading the body. The authentication chapter closes that leak by answering every login failure with the same generic Unauthorized, and the tests on this page check the body for the same reason: the status says the request failed, and the body says how much the server gave away while failing.
The rule for this page is simple: assert the status and the body together, in every negative test. The expected body is always the same value:
assert_eq!(body, json!({ "error": "unauthorized" }));
That one line is the whole of the leak check. When it passes for every failure case, the server's answers are indistinguishable from each other, and a caller probing the route learns nothing except that the request was refused.
The Four Failure Cases
The extractor can fail in four distinct ways, and each one deserves its own test, because each one exercises a different line of the verification code. A missing header fails in bearer_token. A garbage token fails in decode. A wrong secret fails in decode too, but for a different reason. An expired token fails in the validation step inside decode. Four tests, one per failure, all expecting the same answer.
No token at all
Shown above. The request carries no Authorization header, the extractor returns Unauthorized before looking at anything else, and the handler never runs.
Garbage token
#[tokio::test]
async fn garbage_token_is_401_with_the_same_body() {
let (status, body) = get_profile(Some("not-a-token".to_string())).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body, json!({ "error": "unauthorized" }));
}
The string not-a-token is not three base64url parts separated by dots, so decode rejects it at once. The test proves the route does not accept a made-up string just because it arrived in the right header. This is the case a beginner most often forgets to test, because a garbage token feels too obviously wrong to bother with, and it is the case an attacker tries first.
Token signed with the wrong secret
use axum_project::{create_token, WRONG_SECRET};
#[tokio::test]
async fn token_signed_with_the_wrong_secret_is_401() {
let token = create_token(1, "user", WRONG_SECRET).unwrap();
let (status, body) = get_profile(Some(token)).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body, json!({ "error": "unauthorized" }));
}
This token is well formed, with real claims and a real signature, but the signature was made with a different secret, "a-different-secret-for-the-wrong-key-test". Verification recomputes the signature with the app's secret, the two do not match, and the token is rejected. The test proves the server checks the signature, not just the shape. A route that only checked that the token had three parts would accept this token, and the test would catch it.
Expired token
use axum_project::{create_token_with_exp, TEST_SECRET};
#[tokio::test]
async fn expired_token_is_401() {
let token = create_token_with_exp(1, "user", TEST_SECRET, 1).unwrap();
let (status, body) = get_profile(Some(token)).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body, json!({ "error": "unauthorized" }));
}
The token is minted with exp set to 1, which is one second after the Unix epoch, in 1970. It is a genuine token, signed with the right secret, for a real user, and it is long past its expiry. decode checks the expiry against the current time as part of its default validation, and rejects it. The test proves the route checks freshness, not just authenticity. Minting the expired token needs a helper that takes the expiry as an argument:
pub fn create_token_with_exp(
user_id: i32,
role: &str,
secret: &str,
exp: usize,
) -> Result<String, AppError> {
let claims = Claims {
sub: user_id,
role: role.to_string(),
exp,
};
let key = EncodingKey::from_secret(secret.as_bytes()).map_err(|_| AppError::InternalError)?;
encode(&Header::default(), &claims, &key).map_err(|_| AppError::InternalError)
}
pub fn create_token(user_id: i32, role: &str, secret: &str) -> Result<String, AppError> {
create_token_with_exp(user_id, role, secret, expiry_in_one_hour())
}
The ordinary create_token is a thin wrapper that passes an expiry one hour in the future. The test uses the longer form directly, with an expiry in the past, to build a token that is valid in every way except freshness.
One Answer for Every Failure:
All four cases answer 401 with the same body. That sameness is deliberate, and it is the same rule the login handler follows for unknown emails and wrong passwords. A caller who tries all four learns nothing from the differences between them, because there are no differences.
The Positive Control
Four negative tests that all pass prove nothing on their own if the route answers 401 to every request, including valid ones. A route that rejects everything passes every negative test and is completely broken. The positive control is the test that proves the route still lets the right requests in:
use axum_project::token_for;
#[tokio::test]
async fn valid_token_is_200_so_the_negative_tests_are_meaningful() {
let (status, body) = get_profile(Some(token_for(1, "user"))).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, json!({ "user_id": 1, "role": "user" }));
}
The name says why the test exists. Without it, the four negative tests could all pass because the extractor rejects everything, and nobody would know. With it, the suite proves both halves: valid tokens pass, and each kind of invalid token fails. Every negative test file needs one positive control, and it should sit next to the negative tests, not in a different file where it is easy to forget.
401 Is Not 403
The last confusion this page has to settle is the difference between 401 and 403, because a test that asserts the wrong one will pass while the server gives clients the wrong advice. The retry test from the authentication chapter settles every case: if logging in again could fix the request, the answer is 401. If logging in again changes nothing, the answer is 403.
A request with no token fails the first way. A login would supply a token, so the answer is 401. A request from a known user with the wrong role fails the second way. A login would return the same user and the same role, so the answer is 403. The admin route shows both:
async fn get_admin(token: Option<String>) -> StatusCode {
let mut builder = Request::builder().uri("/admin");
if let Some(token) = token {
builder = builder.header("authorization", format!("Bearer {token}"));
}
auth_app(test_state().await)
.oneshot(builder.body(Body::empty()).unwrap())
.await
.unwrap()
.status()
}
#[tokio::test]
async fn valid_token_with_the_wrong_role_is_403_not_401() {
let status = get_admin(Some(token_for(1, "user"))).await;
assert_eq!(status, StatusCode::FORBIDDEN);
}
#[tokio::test]
async fn admin_token_reaches_the_admin_route() {
let status = get_admin(Some(token_for(1, "admin"))).await;
assert_eq!(status, StatusCode::OK);
}
#[tokio::test]
async fn missing_token_on_admin_is_401_not_403() {
let status = get_admin(None).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
}
Three tests, three answers, and the order in the code is what makes them right. The extractor runs first, so a missing token is 401 before the role is ever looked at. The role check runs second, so a valid token with role user on the admin route is 403. A handler that checked the role first would answer 403 to a request with no token at all, which is wrong twice over: it claims to know who is asking when it does not, and it tells the client to stop trying when a login would have fixed the request.
No token -> 401 Unauthorized (a login would fix it)
Garbage token -> 401 Unauthorized (a login would fix it)
Wrong secret -> 401 Unauthorized (a login would fix it)
Expired token -> 401 Unauthorized (a login would fix it)
Valid token, wrong role -> 403 Forbidden (a login changes nothing)
Valid token, right role -> 200 OK
The client branches on that number. On a 401, a well-behaved client tries the refresh flow, and if that fails, it sends the person to the login screen. On a 403, it shows a refusal message and does not retry, because neither a refresh nor a login would help. A server that answers 403 to a missing token sends the client down the wrong branch, and a server that answers 401 to a wrong role sends the client into a loop of refreshing a token that will never gain the role.
The Whole Case Table in One Test File
The eight tests on this page, in the order they run, cover the contract end to end. Each one uses the same two helpers, get_profile and get_admin, and each one asserts the exact status and, where a body is checked, the exact body:
| Request | Status | Body |
|---|---|---|
No token to /profile | 401 | {"error": "unauthorized"} |
Garbage token to /profile | 401 | {"error": "unauthorized"} |
Wrong-secret token to /profile | 401 | {"error": "unauthorized"} |
Expired token to /profile | 401 | {"error": "unauthorized"} |
Valid token to /profile | 200 | {"user_id": 1, "role": "user"} |
Valid user token to /admin | 403 | {"error": "forbidden"} |
Valid admin token to /admin | 200 | {"message": "welcome, admin"} |
No token to /admin | 401 | {"error": "unauthorized"} |
The table is worth keeping in the test file as a comment, or in the page as documentation, because it is the contract a future change has to preserve. If someone edits the extractor and one row changes, the table says which row, and the test says what it should have been.
Common Beginner Mistakes
Asserting only the status
// Wrong - passes while the body leaks which check failed
let (status, _) = get_profile(None).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
The underscore throws the body away, and with it the only evidence of a leak. A handler that returns {"error": "no account with that email"} for one failure and {"error": "wrong password"} for another passes this test and leaks account existence. Assert the body in every negative test, with the exact expected JSON.
Minting the bad token with the right secret
// Wrong - this token is valid, so the test checks the happy path by mistake
let token = create_token(1, "user", TEST_SECRET).unwrap();
let (status, _) = get_profile(Some(token)).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
A test that means to check the wrong-secret case but mints with the real secret will fail with a 200, and the failure looks like the extractor is broken. Read the test failure first: a 200 where a 401 was expected usually means the test built a valid token by accident. Check the secret argument before suspecting the server.
Testing only the happy path
A suite with only the valid-token test passes while the route accepts garbage, because nothing ever sent garbage. Negative tests are not extra credit. They are the proof the lock works, and a protected route without them is untested where it matters most.
Using an expiry that is still in the future
// Wrong - exp 2_000_000_000 is the year 2033, so this token is not expired
let token = create_token_with_exp(1, "user", TEST_SECRET, 2_000_000_000).unwrap();
An expiry is a number of seconds since the Unix epoch, and large numbers are far in the future. The authentication chapter uses 2_000_000_000 as a healthy expiry in its round-trip example, and that same number in an expired-token test builds a valid token. For an expired token, use a small number like 1, or compute the current time and subtract an hour. The test fails with a 200 when the number is wrong, and the number is the first thing to check.
A 200 Where a 401 Was Expected Means the Test Built a Good Token:
When a negative test fails with status 200, the extractor accepted the token, which almost always means the test minted a valid token by mistake: the right secret, a future expiry, and a well-formed shape. Check the token the test built before changing the extractor. The extractor is usually right, and the test is usually the thing that needs fixing.
Final Complete Example
The whole test file, with both helpers and all eight tests, against the app from the previous page:
use axum::{body::Body, http::{Request, StatusCode}};
use axum_project::{
WRONG_SECRET, auth_app, create_token, create_token_with_exp, test_state, token_for, TEST_SECRET,
};
use http_body_util::BodyExt;
use serde_json::{Value, json};
use tower::ServiceExt;
async fn get_profile(token: Option<String>) -> (StatusCode, Value) {
let mut builder = Request::builder().uri("/profile");
if let Some(token) = token {
builder = builder.header("authorization", format!("Bearer {token}"));
}
let response = auth_app(test_state().await)
.oneshot(builder.body(Body::empty()).unwrap())
.await
.unwrap();
let status = response.status();
let bytes = response.into_body().collect().await.unwrap().to_bytes();
(status, serde_json::from_slice(&bytes).unwrap())
}
async fn get_admin(token: Option<String>) -> StatusCode {
let mut builder = Request::builder().uri("/admin");
if let Some(token) = token {
builder = builder.header("authorization", format!("Bearer {token}"));
}
auth_app(test_state().await)
.oneshot(builder.body(Body::empty()).unwrap())
.await
.unwrap()
.status()
}
#[tokio::test]
async fn no_token_is_401_with_the_generic_body() {
let (status, body) = get_profile(None).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body, json!({ "error": "unauthorized" }));
}
#[tokio::test]
async fn garbage_token_is_401_with_the_same_body() {
let (status, body) = get_profile(Some("not-a-token".to_string())).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body, json!({ "error": "unauthorized" }));
}
#[tokio::test]
async fn token_signed_with_the_wrong_secret_is_401() {
let token = create_token(1, "user", WRONG_SECRET).unwrap();
let (status, body) = get_profile(Some(token)).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body, json!({ "error": "unauthorized" }));
}
#[tokio::test]
async fn expired_token_is_401() {
let token = create_token_with_exp(1, "user", TEST_SECRET, 1).unwrap();
let (status, body) = get_profile(Some(token)).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body, json!({ "error": "unauthorized" }));
}
#[tokio::test]
async fn valid_token_is_200_so_the_negative_tests_are_meaningful() {
let (status, body) = get_profile(Some(token_for(1, "user"))).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, json!({ "user_id": 1, "role": "user" }));
}
#[tokio::test]
async fn valid_token_with_the_wrong_role_is_403_not_401() {
let status = get_admin(Some(token_for(1, "user"))).await;
assert_eq!(status, StatusCode::FORBIDDEN);
}
#[tokio::test]
async fn admin_token_reaches_the_admin_route() {
let status = get_admin(Some(token_for(1, "admin"))).await;
assert_eq!(status, StatusCode::OK);
}
#[tokio::test]
async fn missing_token_on_admin_is_401_not_403() {
let status = get_admin(None).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
}
Run the tests with:
cargo test --test auth_401_test
All eight tests pass. The four negative cases agree with each other byte for byte, the positive control proves the route still opens for a valid token, and the admin cases prove the 401 and 403 answers land on the right requests.
Summary
A protected route is tested by its refusals, and the refusals are only meaningful when they are checked exactly. Four different failures, one identical answer, and a positive control that proves the door still opens, is the complete shape. The body check is what turns a status check into a leak check, and the 401 versus 403 split is what turns a refusal into advice the client can act on: log in again, or stop asking.
The pattern generalises beyond authentication. Any handler that refuses requests should be tested the same way: every way it can refuse, the exact status and body for each, and one test that proves it still accepts the request it should accept. The next pages apply the same discipline to stranger transports, where the request is not a plain HTTP call at all, but a WebSocket handshake and a streaming response.