-
Notifications
You must be signed in to change notification settings - Fork 13
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feature: learned axum middleware and finished auth middleware
- Loading branch information
Showing
9 changed files
with
352 additions
and
6 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
use axum::{ | ||
extract::{FromRequestParts, Request, State}, | ||
http::StatusCode, | ||
middleware::Next, | ||
response::{IntoResponse, Response}, | ||
}; | ||
use axum_extra::{ | ||
headers::{authorization::Bearer, Authorization}, | ||
TypedHeader, | ||
}; | ||
use tracing::warn; | ||
|
||
use crate::AppState; | ||
|
||
pub async fn verify_token(State(state): State<AppState>, req: Request, next: Next) -> Response { | ||
let (mut parts, body) = req.into_parts(); | ||
let req = | ||
match TypedHeader::<Authorization<Bearer>>::from_request_parts(&mut parts, &state).await { | ||
Ok(TypedHeader(Authorization(bearer))) => { | ||
let token = bearer.token(); | ||
match state.dk.verify(token) { | ||
Ok(user) => { | ||
let mut req = Request::from_parts(parts, body); | ||
req.extensions_mut().insert(user); | ||
req | ||
} | ||
Err(e) => { | ||
let msg = format!("verify token failed: {}", e); | ||
warn!(msg); | ||
return (StatusCode::FORBIDDEN, msg).into_response(); | ||
} | ||
} | ||
} | ||
Err(e) => { | ||
let msg = format!("parse Authorization header failed: {}", e); | ||
warn!(msg); | ||
return (StatusCode::UNAUTHORIZED, msg).into_response(); | ||
} | ||
}; | ||
|
||
next.run(req).await | ||
} |
Oops, something went wrong.