You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
#[debug_middleware]
async fn auth_middleware(
Extension(_state): Extension<Arc<AppState>>,
jar: CookieJar,
mut request: Request,
next: Next,
) -> Result<Response, StatusCode> {
debug!("Auth middleware");
// First we try to authenticate using the bearer token
let authorization_header = request.headers().get(header::AUTHORIZATION);
if authorization_header.is_none() {
// Fallback to the authetication token cookie
let auth_cookie = jar.get("auth_token");
if auth_cookie.is_none() {
// Nothing to work with
return Err(StatusCode::UNAUTHORIZED);
}
}
// Determine the authorization token to check
let argument = match authorization_header {
Some(header) => {
let token_str = header
.to_str()
.unwrap()
.trim_start_matches("Bearer ")
.to_string();
token_str
}
None => jar.get("auth_token").unwrap().value().to_string(),
};
// Perform the actual check
let decode_result = decode::<Claims>(
argument.as_str(),
&DecodingKey::from_secret(TOKEN_SECRET.as_bytes()),
&Validation::default(),
);
if decode_result.is_err() {
// Invalid or expired token
return Err(StatusCode::FORBIDDEN);
}
// Token is valid, attach user data to the request
let claims = decode_result.unwrap().claims;
let authenticated_user = AuthenticatedUser {
user_id: claims.user_id,
remember_me: claims.remember_me,
};
debug!("Authenticated user extension:");
request.extensions_mut().insert(authenticated_user);
Ok(next.run(request).await)
}
The handler:
#[axum::debug_handler]
#[utoipa::path(
get,
path = "/renew",
tag = "auth",
security(
("cookie" = []),
("bearer" = [])
),
responses(
(status = OK, description = "Token renewed", body = LoginResponse),
(status = FORBIDDEN, description = "Invalid credentials")
)
)]
pub async fn get_renew(
Extension(authenticated_user): Extension<AuthenticatedUser>,
jar: CookieJar,
) -> (StatusCode, CookieJar, Json<LoginResponse>) {
// TODO: authentication middleware
// TODO: fetch data from the request extensions
// Generate the authorization token
let authorization_data =
generate_authorization_token(authenticated_user.user_id, authenticated_user.remember_me);
// Get the authorization response cookie
let cookie = Cookie::build(("auth_token", authorization_data.token.clone()))
.path("/")
.expires(authorization_data.expiration_date)
.secure(true)
.http_only(true);
// All good
(
StatusCode::OK,
jar.add(cookie),
Json(LoginResponse {
message: "User authenticated".to_string(),
auth_token: Some(authorization_data.token),
}),
)
}
I am basing this approach on @juhaku 's reply to #1296
The text was updated successfully, but these errors were encountered:
rbaprado
changed the title
Middleware not running
Middleware not running (Axum)
Feb 6, 2025
Maybe I am missing something here, but my middleware does not get called prior the handler.
Here's my router setup:
The middleware function:
The handler:
I am basing this approach on @juhaku 's reply to #1296
The text was updated successfully, but these errors were encountered: