Auth headers on upgrade
Learn how to check the Authorization header before a WebSocket upgrade, reject unauthenticated clients with 401, and pass the verified user into the socket loop
A WebSocket connection that anyone can open is a room with no door. The fix is to check the Authorization header before the upgrade, and to refuse the request with 401 when the header is missing or the token is bad. The check must happen before on_upgrade is called, because once the upgrade runs, the socket is open and the client is in. The token itself is a short signed string that proves who the client is, and this page reuses the exact token shapes from the authentication chapter: the same Claims, the same AuthUser, the same bearer_token helper, and the same verify_token helper.
Where This Fits
The previous page built a room where every message reaches everyone, and this page locks the room's door. The broadcast server let anyone in, and this page lets in only the clients that prove who they are. The upgrade is the moment the door opens, so the check belongs at the upgrade, not after it.
Think of a members-only club. The doorkeeper checks the membership card before opening the door, and a guest without a card never gets inside, no matter how politely they ask. The handler is the doorkeeper, the token is the card, and the upgrade is the door. Checking the card after the door is open is not checking at all.
The Smallest Working Version
This server has a login route that mints a token and a WebSocket route that checks it. The login route is deliberately small: it takes a user id and a role, signs them into a token, and returns it, without checking a password, so the page can focus on the upgrade check. A real login checks the password against a database first, as the authentication chapter shows.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = { version = "0.8", features = ["ws"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
jsonwebtoken = { version = "12", features = ["rust_crypto"] }
thiserror = "2.0"
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
#[derive(Debug, thiserror::Error)]
pub enum AppError {
#[error("unauthorized")]
Unauthorized,
#[error("something went wrong")]
InternalError,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let status = match &self {
AppError::Unauthorized => StatusCode::UNAUTHORIZED,
AppError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
};
let body = Json(json!({ "error": self.to_string() }));
(status, body).into_response()
}
}
pub type HandlerResult<T> = Result<T, AppError>;
use axum::http::{HeaderMap, header};
use jsonwebtoken::{DecodingKey, Validation, decode};
use serde::{Deserialize, Serialize};
use crate::errors::AppError;
#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
pub sub: i32,
pub role: String,
pub exp: usize,
}
#[derive(Debug, Clone)]
pub struct AuthUser {
pub user_id: i32,
pub role: String,
}
pub fn verify_token(token: &str, secret: &str) -> Result<Claims, AppError> {
let key = DecodingKey::from_secret(secret.as_bytes()).map_err(|error| {
eprintln!("decoding key error: {error}");
AppError::Unauthorized
})?;
let data = decode::<Claims>(token, &key, &Validation::default()).map_err(|error| {
eprintln!("token decode error: {error}");
AppError::Unauthorized
})?;
Ok(data.claims)
}
pub 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 "))
}
use std::time::{SystemTime, UNIX_EPOCH};
use axum::{
extract::ws::{Message, WebSocket, WebSocketUpgrade},
http::HeaderMap,
response::Response,
routing::{get, post},
Json, Router,
};
use jsonwebtoken::{EncodingKey, Header, encode};
use serde::Deserialize;
use serde_json::json;
use axum_project::{
auth::{bearer_token, verify_token, AuthUser, Claims},
errors::{AppError, HandlerResult},
};
#[derive(Debug, Deserialize)]
struct LoginRequest {
user_id: i32,
role: String,
}
fn now_secs() -> usize {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs() as usize
}
async fn login(Json(body): Json<LoginRequest>) -> HandlerResult<Json<serde_json::Value>> {
let secret = std::env::var("JWT_SECRET").map_err(|_| AppError::InternalError)?;
let claims = Claims {
sub: body.user_id,
role: body.role,
exp: now_secs() + 3600,
};
let key = EncodingKey::from_secret(secret.as_bytes()).map_err(|error| {
eprintln!("encoding key error: {error}");
AppError::InternalError
})?;
let token = encode(&Header::default(), &claims, &key).map_err(|error| {
eprintln!("token encode error: {error}");
AppError::InternalError
})?;
Ok(Json(json!({ "token": token })))
}
async fn ws_handler(headers: HeaderMap, ws: WebSocketUpgrade) -> Result<Response, AppError> {
let Some(token) = bearer_token(&headers) else {
return Err(AppError::Unauthorized);
};
let secret = std::env::var("JWT_SECRET").map_err(|_| AppError::Unauthorized)?;
let claims = verify_token(token, &secret)?;
let user = AuthUser {
user_id: claims.sub,
role: claims.role,
};
Ok(ws.on_upgrade(|socket| handle_socket(socket, user)))
}
async fn handle_socket(mut socket: WebSocket, user: AuthUser) {
while let Some(msg) = socket.recv().await {
let Ok(msg) = msg else { return };
if let Message::Text(text) = msg {
let reply = format!("user {} says: {text}", user.user_id);
if socket.send(Message::Text(reply.into())).await.is_err() {
return;
}
}
}
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/login", post(login))
.route("/ws", get(ws_handler));
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 project needs a src/lib.rs that declares the modules, so main.rs can import them:
pub mod auth;
pub mod errors;
Run it with the signing secret set, using a test-only value for local development:
JWT_SECRET="test-secret-only-for-local-development" cargo run
Log in to get a token, using the login route:
curl -s -X POST http://127.0.0.1:3000/login \
-H "Content-Type: application/json" \
-d '{"user_id": 7, "role": "admin"}'
{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjcsInJvbGUiOiJhZG1pbiIsImV4cCI6MTc5NDY0ODE1NH0.XXXX"}
A real WebSocket client sends that token in the Authorization header when it connects. The live run below, from the verification project, shows a client connecting with the token, sending hello, and receiving the reply that carries its user id:
client: handshake status 101 Switching Protocols
client received: Text(Utf8Bytes(b"user 7 says: hello"))
And the same client connecting without a token is refused before any upgrade happens:
client: handshake failed as expected: HTTP error: 401 Unauthorized
Working Setup:
If the client with a token gets 101 and its echo carries its user id, and the client without a token gets 401, the check runs before the upgrade and the verified user reaches the loop. If the client without a token gets 101, the check is after the upgrade or missing, and the mistakes section below covers the cause.
Understanding the Check Line by Line
The handler is short, and the order of its lines is the whole lesson.
Reading the header first
async fn ws_handler(headers: HeaderMap, ws: WebSocketUpgrade) -> Result<Response, AppError> {
let Some(token) = bearer_token(&headers) else {
return Err(AppError::Unauthorized);
};
The handler takes two arguments: the headers and the upgrade extractor. bearer_token reads the Authorization header, strips the Bearer prefix, and returns the token, or None when the header is missing, not text, or has the wrong scheme. The let ... else returns the unauthorized error at once when there is no token, before anything else runs. The handler returns a Result<Response, AppError>, so the error becomes the response: status 401 with the body {"error":"unauthorized"}.
Reading the secret and verifying
let secret = std::env::var("JWT_SECRET").map_err(|_| AppError::Unauthorized)?;
let claims = verify_token(token, &secret)?;
let user = AuthUser {
user_id: claims.sub,
role: claims.role,
};
The secret is read from the environment, and a missing secret maps to the unauthorized error, not the internal error, because the server cannot prove who is asking and must fail closed. Failing closed means refusing the request when the server cannot prove it is safe, rather than letting it through. verify_token checks the signature and the expiry, and the ? returns its unauthorized error early when the token fails. Only a verified token reaches the last lines, which copy the two claims into an AuthUser: claims.sub, the user id, becomes user_id, and claims.role becomes role. The exp claim is not copied, because the verification already proved the token is fresh, and the handler does not need it.
Upgrading only after the check
Ok(ws.on_upgrade(|socket| handle_socket(socket, user)))
}
on_upgrade is called only after the check passed, and the closure moves the verified user into the socket callback. An unauthenticated request never reaches this line, so it never gets a socket, and the server never spends a task on it. The handler's return type wraps the upgrade response in Ok, because the handler returns a Result, and the error arms above return the Err side.
The Concept Behind Checking Before the Upgrade
The upgrade is a point of no return. Once on_upgrade runs, the 101 is sent, the socket is open, and the client is inside, and any check after that point is a check on a client that is already connected. The client could have sent messages in the meantime, and the server would have to decide what to do with them. Checking first avoids all of that: the request is either a verified user getting a socket, or a refused request getting a 401, and there is no state in between. The shape is the same as a doorkeeper checking a card before opening the door, and the reason is the same: a check after entry is not a check.
Why the Shapes Match the Authentication Chapter
Claims, AuthUser, bearer_token, and verify_token are copied unchanged from the authentication chapter, and they must stay unchanged. The token a client uses for a WebSocket is the same token it uses for a protected HTTP route, minted by the same login, signed with the same secret, and verified by the same function. A project that invents a second token format for WebSockets ends up with two logins, two secrets, and two ways to get the check wrong. Reusing the shapes means a client logs in once and uses the token everywhere, and a server change to the verification logic fixes every route at once, including the WebSocket ones.
A Subtlety Worth Knowing: the Extractor Runs Before the Body
The check in the handler body runs after the upgrade extractor succeeds, because extractors run before the handler body. That has one observable consequence, verified live against the server above. A plain HTTP request to /ws without upgrade headers gets the extractor's 400, even without a token:
curl -i http://127.0.0.1:3000/ws
HTTP/1.1 400 Bad Request
content-type: text/plain; charset=utf-8
content-length: 43
Connection header did not include 'upgrade'
A real WebSocket client, which sends proper upgrade headers, reaches the body check and gets the 401 when it has no token, as the live run above shows. The security property holds either way: no socket is ever created for an unauthenticated request, because a plain request is rejected by the extractor and a WebSocket request is rejected by the check. The two rejections answer different questions, and both refuse the request. A server that wants the 401 to win even for plain HTTP requests needs the check as an extractor, which is the variation below.
Two Rejections, One Outcome:
A plain request gets 400 from the extractor, and a WebSocket request without a token gets 401 from the check. Both are refusals, and neither creates a socket. The difference only matters to a client that reads the status code, and a WebSocket client always sends upgrade headers, so it always sees the 401 when it has no token.
A Richer Example With a Role Check
The verified user carries a role, and the handler can refuse a role as well as a missing token. This version lets only admin users open the socket, and answers anyone else with 403 Forbidden, which is the status for a client that is authenticated but not allowed:
async fn ws_handler(headers: HeaderMap, ws: WebSocketUpgrade) -> Result<Response, AppError> {
let Some(token) = bearer_token(&headers) else {
return Err(AppError::Unauthorized);
};
let secret = std::env::var("JWT_SECRET").map_err(|_| AppError::Unauthorized)?;
let claims = verify_token(token, &secret)?;
let user = AuthUser {
user_id: claims.sub,
role: claims.role,
};
if user.role != "admin" {
return Err(AppError::Forbidden);
}
Ok(ws.on_upgrade(|socket| handle_socket(socket, user)))
}
The role check needs a Forbidden variant on the error type, with the message forbidden and status 403, matching the shared error shape from the authentication chapter. A user with the role user logs in fine, gets a valid token, and is refused at the upgrade with 403 and the body {"error":"forbidden"}. The distinction between 401 and 403 matters: 401 means "I do not know who you are", and 403 means "I know who you are, and you may not do this". A client that gets 403 knows its token works and its role does not, and a client that gets 401 knows its token is missing or bad.
Variations
Checking with an extractor so 401 wins first
The body check is simple, and it has the 400-first subtlety above. An extractor moves the check before the upgrade extractor, because extractors run in argument order, and the first extractor to fail decides the answer. This version defines a small extractor that verifies the token and builds the user, and lists it before WebSocketUpgrade:
use axum::{
extract::FromRequestParts,
http::{HeaderMap, header, request::Parts},
};
pub struct WsUser(pub AuthUser);
impl FromRequestParts<()> for WsUser {
type Rejection = AppError;
async fn from_request_parts(
parts: &mut Parts,
_state: &(),
) -> Result<Self, Self::Rejection> {
let Some(token) = bearer_token(&parts.headers) else {
return Err(AppError::Unauthorized);
};
let secret = std::env::var("JWT_SECRET").map_err(|_| AppError::Unauthorized)?;
let claims = verify_token(token, &secret)?;
Ok(WsUser(AuthUser {
user_id: claims.sub,
role: claims.role,
}))
}
}
async fn ws_handler_checked(WsUser(user): WsUser, ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(|socket| handle_socket(socket, user))
}
The state type in FromRequestParts<()> must match the router's state, and this router has no state, so it is (). A router built with state, such as a broadcast channel, would need that state type here instead. The live run of this exact shape, from the verification project, shows the difference:
curl -i http://127.0.0.1:3000/ws2
HTTP/1.1 401 Unauthorized
content-type: application/json
content-length: 24
{"error":"unauthorized"}
A plain request without a token now gets 401, because the extractor runs first and refuses it before the upgrade extractor ever sees it. A request with a token but without upgrade headers still gets the extractor's 400, because the auth passed and the upgrade check failed next. The extractor version is the stronger form, and the body version is the simpler one. Use the extractor version when the 401 must win for every request, and the body version when the handler is small and the subtlety does not matter.
Passing the token in the query string
Some clients cannot set headers when they open a WebSocket, notably browsers using the built-in WebSocket object, which sends no custom headers. Those clients pass the token in the query string instead, such as /ws?token=..., and the handler reads it with a Query extractor. The query string is visible in logs and in browser history, so it is less private than a header, and a token in a URL can leak through a shared link. The header form is preferred whenever the client can send it, and the query form is the fallback for clients that cannot. The verification of the token is identical either way: the same verify_token, the same 401 on failure, and the same check before the upgrade.
Rejecting an expired token
An expired token fails verification in verify_token, because the default validation checks the exp claim, and the handler answers 401 like any other bad token. The client must log in again to get a fresh token, and then reconnect. A WebSocket client that stays connected for longer than the token's lifetime is not affected, because the token is checked once, at the upgrade, and the open socket does not re-check it. That is worth knowing: a token that expires mid-connection does not close the connection, and a server that needs to end long sessions must check again, or close the socket itself when the session should end.
A Plain Text Diagram of the Authenticated Upgrade
The request passes the auth check before it reaches the upgrade:
client sends GET with upgrade headers + Authorization: Bearer <token>
|
v
bearer_token reads the header
|
+-- no token --> 401 + {"error": "unauthorized"}
|
v
verify_token checks the signature and expiry
|
+-- bad or expired --> 401 + {"error": "unauthorized"}
|
v
AuthUser built from the claims
|
v
ws.on_upgrade runs, 101 is sent
|
v
socket loop runs with the verified user
Every failure ends before the upgrade, and the loop only ever sees a verified user. The diagram has no branch after the upgrade, because there is no auth decision left to make there.
Testing It
The tests below cover the three outcomes: a good token upgrades, a missing token is refused, and a bad token is refused. The token helper mints a token with the same claims shape, and the tests send real WebSocket handshakes through a live server. They need tokio-tungstenite as a dev-dependency:
[dev-dependencies]
tokio-tungstenite = "0.29"
futures-util = "0.3"
http = "1"
use std::time::{SystemTime, UNIX_EPOCH};
use axum::{
extract::ws::{Message, WebSocket, WebSocketUpgrade},
http::HeaderMap,
response::Response,
routing::get,
Router,
};
use axum_project::{
auth::{bearer_token, verify_token, AuthUser, Claims},
errors::AppError,
};
use futures_util::{SinkExt, StreamExt};
use jsonwebtoken::{EncodingKey, Header, encode};
use tokio_tungstenite::connect_async;
const SECRET: &str = "test-secret-only-for-local-development";
fn now_secs() -> usize {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs() as usize
}
fn make_token(user_id: i32, role: &str, secret: &str) -> String {
let claims = Claims {
sub: user_id,
role: role.to_string(),
exp: now_secs() + 3600,
};
let key = EncodingKey::from_secret(secret.as_bytes()).unwrap();
encode(&Header::default(), &claims, &key).unwrap()
}
async fn ws_handler(headers: HeaderMap, ws: WebSocketUpgrade) -> Result<Response, AppError> {
let Some(token) = bearer_token(&headers) else {
return Err(AppError::Unauthorized);
};
let secret = std::env::var("JWT_SECRET").map_err(|_| AppError::Unauthorized)?;
let claims = verify_token(token, &secret)?;
let user = AuthUser {
user_id: claims.sub,
role: claims.role,
};
Ok(ws.on_upgrade(|socket| handle_socket(socket, user)))
}
async fn handle_socket(mut socket: WebSocket, user: AuthUser) {
while let Some(msg) = socket.recv().await {
let Ok(msg) = msg else { return };
if let Message::Text(text) = msg {
let reply = format!("user {} says: {text}", user.user_id);
if socket.send(Message::Text(reply.into())).await.is_err() {
return;
}
}
}
}
async fn start_server() -> String {
let app = Router::new().route("/ws", get(ws_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
format!("ws://{addr}/ws")
}
fn request_with_token(url: &str, token: Option<&str>) -> http::Request<()> {
let host = url.strip_prefix("ws://").unwrap().split('/').next().unwrap();
let mut builder = http::Request::builder()
.uri(url)
.header("Host", host)
.header("Connection", "Upgrade")
.header("Upgrade", "websocket")
.header("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==")
.header("Sec-WebSocket-Version", "13");
if let Some(token) = token {
builder = builder.header("Authorization", format!("Bearer {token}"));
}
builder.body(()).unwrap()
}
#[tokio::test]
async fn upgrade_with_valid_token_echoes_with_user_id() {
let url = start_server().await;
let token = make_token(7, "admin", SECRET);
let (mut ws, response) = connect_async(request_with_token(&url, Some(&token)))
.await
.unwrap();
assert_eq!(response.status(), 101);
ws.send(tokio_tungstenite::tungstenite::Message::Text("hello".into()))
.await
.unwrap();
let msg = ws.next().await.unwrap().unwrap();
assert_eq!(
msg,
tokio_tungstenite::tungstenite::Message::Text("user 7 says: hello".into())
);
ws.close(None).await.unwrap();
}
#[tokio::test]
async fn upgrade_without_token_is_unauthorized() {
let url = start_server().await;
let result = connect_async(request_with_token(&url, None)).await;
assert!(result.is_err());
let error = format!("{}", result.unwrap_err());
assert!(error.contains("401"));
}
#[tokio::test]
async fn upgrade_with_wrongly_signed_token_is_unauthorized() {
let url = start_server().await;
let token = make_token(7, "admin", "a-different-secret");
let result = connect_async(request_with_token(&url, Some(&token))).await;
assert!(result.is_err());
let error = format!("{}", result.unwrap_err());
assert!(error.contains("401"));
}
Run them with:
JWT_SECRET="test-secret-only-for-local-development" cargo test --test auth_ws_test
test upgrade_with_valid_token_echoes_with_user_id ... ok
test upgrade_without_token_is_unauthorized ... ok
test upgrade_with_wrongly_signed_token_is_unauthorized ... ok
The tests set the secret through the environment, because the handler reads JWT_SECRET at request time. The first test asserts the 101 and the echo carrying user id 7. The second and third assert the handshake fails with a 401, for a missing token and for a token signed with the wrong secret. The request builder in the test carries the headers a WebSocket client sends, including the upgrade headers and a fixed key, because connect_async with a hand-built request needs them present.
The Test Secret Must Match the Handler Secret:
The tests mint tokens with the constant SECRET and the handler reads JWT_SECRET from the environment, so the two must be the same string or every test fails with 401. The command above sets the environment variable to the same test-only value. A real deployment uses a long random secret that never appears in code, and the test value is only for local development.
Common Beginner Mistakes
Checking the token after on_upgrade
// Wrong - the socket is already open when the check runs
async fn ws_handler(ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(|socket| async move {
let mut socket = socket;
while let Some(msg) = socket.recv().await {
let Ok(msg) = msg else { return };
let _ = msg;
}
})
}
This handler upgrades every request without checking anything, and there is no token check in the callback either. The fix is the check before on_upgrade, as the working version shows. A check inside the callback is too late: the client is already connected, and the server must decide what to do with a connection it should never have opened. The check belongs in the handler, before the upgrade.
Taking WebSocketUpgrade before the headers
// Wrong - the order of arguments does not move the body check earlier
async fn ws_handler(ws: WebSocketUpgrade, headers: HeaderMap) -> Result<Response, AppError> {
let Some(token) = bearer_token(&headers) else {
return Err(AppError::Unauthorized);
};
Ok(ws.on_upgrade(|socket| handle_socket(socket, AuthUser { user_id: 0, role: "user".to_string() })))
}
The argument order does not change when the body check runs: the extractor still runs first, and the body check still runs after it. Swapping the arguments changes nothing about the 400-first subtlety, and the example above has a second mistake, a hard-coded user that was never verified. The fix for the order is the extractor version, where the auth extractor is listed first and runs first. The fix for the user is to build it from the verified claims, never from a literal.
Building AuthUser from an unverified token
// Wrong - decoding the payload by hand skips the signature check
let claims: Claims = serde_json::from_slice(&decoded_payload).unwrap();
let user = AuthUser { user_id: claims.sub, role: claims.role };
A token's payload is only base64, not encryption, and anyone can write any payload they like. Decoding it by hand produces a user the server never proved, and every handler that takes it trusts a stranger. The fix is verify_token, which checks the signature and the expiry before returning the claims. An AuthUser must only ever be built from claims that verify_token returned, and that rule is what makes the type worth having.
Returning 403 for a missing token
// Wrong - a missing token is unauthenticated, not forbidden
let Some(token) = bearer_token(&headers) else {
return Err(AppError::Forbidden);
};
A missing token means the server does not know who is asking, which is 401 Unauthorized. A 403 Forbidden means the server knows who is asking and refuses them anyway, which is the role check. Mixing the two up teaches clients the wrong lesson: a client that gets 403 for a missing token tries a different role instead of logging in. The fix is 401 for missing or bad tokens, and 403 only for a verified user who lacks the role.
Putting the secret in the code
// Wrong - a secret in the source is a secret shared with everyone who reads the repo
let secret = "my-secret-key";
let claims = verify_token(token, secret)?;
A secret written in the code ships with the repository, appears in the binary, and cannot be changed without a rebuild. The fix is the environment variable, std::env::var("JWT_SECRET"), with a long random value set where the server runs, and a test-only value for local development. The secret is configuration, not code, and it belongs outside the repository.
Final Complete Example
Here is everything from this page put together: the login route, the upgrade check, the extractor version, and the socket loop that answers with the user id.
use std::time::{SystemTime, UNIX_EPOCH};
use axum::{
extract::ws::{Message, WebSocket, WebSocketUpgrade},
http::HeaderMap,
response::Response,
routing::{get, post},
Json, Router,
};
use jsonwebtoken::{EncodingKey, Header, encode};
use serde::Deserialize;
use serde_json::json;
use axum_project::{
auth::{bearer_token, verify_token, AuthUser, Claims},
errors::{AppError, HandlerResult},
};
#[derive(Debug, Deserialize)]
struct LoginRequest {
user_id: i32,
role: String,
}
fn now_secs() -> usize {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs() as usize
}
async fn login(Json(body): Json<LoginRequest>) -> HandlerResult<Json<serde_json::Value>> {
let secret = std::env::var("JWT_SECRET").map_err(|_| AppError::InternalError)?;
let claims = Claims {
sub: body.user_id,
role: body.role,
exp: now_secs() + 3600,
};
let key = EncodingKey::from_secret(secret.as_bytes()).map_err(|error| {
eprintln!("encoding key error: {error}");
AppError::InternalError
})?;
let token = encode(&Header::default(), &claims, &key).map_err(|error| {
eprintln!("token encode error: {error}");
AppError::InternalError
})?;
Ok(Json(json!({ "token": token })))
}
async fn ws_handler(headers: HeaderMap, ws: WebSocketUpgrade) -> Result<Response, AppError> {
let Some(token) = bearer_token(&headers) else {
return Err(AppError::Unauthorized);
};
let secret = std::env::var("JWT_SECRET").map_err(|_| AppError::Unauthorized)?;
let claims = verify_token(token, &secret)?;
let user = AuthUser {
user_id: claims.sub,
role: claims.role,
};
Ok(ws.on_upgrade(|socket| handle_socket(socket, user)))
}
async fn handle_socket(mut socket: WebSocket, user: AuthUser) {
while let Some(msg) = socket.recv().await {
let Ok(msg) = msg else { return };
if let Message::Text(text) = msg {
let reply = format!("user {} says: {text}", user.user_id);
if socket.send(Message::Text(reply.into())).await.is_err() {
return;
}
}
}
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/login", post(login))
.route("/ws", get(ws_handler));
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();
}
Run the checks with these commands:
cargo check
JWT_SECRET="test-secret-only-for-local-development" cargo test --test auth_ws_test
JWT_SECRET="test-secret-only-for-local-development" cargo run
Summary
Authentication on a WebSocket route is a check before the upgrade, and the check reuses the same token shapes as the rest of the server: bearer_token reads the header, verify_token proves the token, and AuthUser carries the verified identity into the loop. The live runs proved the boundary exactly, a client with a token got 101 and an echo carrying its user id, a client without one got 401, and a plain request got the extractor's 400 before either check could run. The decision to carry forward is the ordering rule: whenever a handler needs a value that must be checked, the check goes before the thing it guards, and when the check must win over the extractor too, it becomes an extractor itself and goes first in the argument list. A socket that opens only for a verified user is a room with a door that actually locks, and the lock is the order of the lines in the handler.