Add auth middleware for protected routes
This commit is contained in:
parent
37cf254c35
commit
78ed205081
1 changed files with 25 additions and 0 deletions
25
src/middleware/auth.rs
Normal file
25
src/middleware/auth.rs
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
use axum::{
|
||||
extract::Request,
|
||||
http::{header, StatusCode},
|
||||
middleware::Next,
|
||||
response::Response,
|
||||
};
|
||||
|
||||
pub async fn require_auth(request: Request, next: Next) -> Result<Response, StatusCode> {
|
||||
let token = request
|
||||
.headers()
|
||||
.get(header::AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.strip_prefix("Bearer "));
|
||||
|
||||
match token {
|
||||
Some(t) => {
|
||||
if crate::auth::jwt::verify(t).is_ok() {
|
||||
Ok(next.run(request).await)
|
||||
} else {
|
||||
Err(StatusCode::UNAUTHORIZED)
|
||||
}
|
||||
}
|
||||
None => Err(StatusCode::UNAUTHORIZED),
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue