Redirect Error Unauthorized to a Page #838
Unanswered
tanto-satu
asked this question in
Q&A
Replies: 2 comments 1 reply
-
|
you can use redirect function |
Beta Was this translation helpful? Give feedback.
1 reply
-
|
I came across this issue. I wasn't able to identify a clean method to redirect using the JWT/auth middleware. My initial workaround to use cookies is as follows. use axum::{debug_handler, http::HeaderMap, response::Redirect};
const SESSION_TOKEN: &str = "session_token";
#[debug_handler]
pub async fn upload(
// auth: auth::JWT, // no longer needed with get_auth_from_header_cookies
headers: HeaderMap,
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
) -> Result<Response> {
let auth = match get_auth_from_header_cookies(&ctx, &headers) {
Ok(auth) => auth,
Err(e) => {
tracing::warn!("failed to auth: {e}");
return Ok(Redirect::to("/").into_response());
}
};
let user = users::Model::find_by_pid(&ctx.db, &auth.claims.pid).await?;
// Do something useful...
views::dashboards::upload(&v)
}
pub fn get_auth_from_header_cookies(
ctx: &AppContext,
headers: &HeaderMap,
) -> Result<auth::JWT, loco_rs::Error> {
let jwt = ctx.config.get_jwt_config()?;
let jar: cookie::CookieJar = cookie::CookieJar::from_headers(headers);
let token = jar
.get(SESSION_TOKEN)
.ok_or(Error::Unauthorized("token is not found".to_string()))?
.to_string()
.strip_prefix(&format!("{SESSION_TOKEN}="))
.ok_or_else(|| Error::Unauthorized("error strip value".to_string()))?
.to_string();
match loco_rs::auth::jwt::JWT::new(&jwt.secret).validate(&token) {
Ok(claims) => Ok(auth::JWT {
claims: claims.claims,
}),
Err(err) => {
tracing::error!("JWT validation error: {}", err);
Err(Error::Unauthorized("token is not valid".to_string()))
}
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Is there any tutorial or example to redirect users to unauthorized pages, when returning error 401 unauthorized because invalid / JWT token not exists? thank you!!
Beta Was this translation helpful? Give feedback.
All reactions