-
Hi guys, i want to try to port my application from fastapi (python) to poem. I am relatively new to rust, so don't blame me if that's a dumb question. I really liked the dependency injection system of fastapi, as you could just depend on some kind of custom middleware and if the user provides the right bearer token, the user object gets directly injected into the route. My problem is that I don't know how to integrate that as a security schema so that it works with the swagger ui. Is there a way to add kind of new types to the as security scheme? Not sure about the current architecture... I am very thankful for any feedback about this!
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
This is the first way, a custom fn parse_user_from_token(token: &str) -> Option<String> {
todo!()
}
#[poem::async_trait]
impl<'a> poem::FromRequest<'a> for User {
async fn from_request(req: &'a Request, body: &mut RequestBody) -> Result<Self> {
use poem::web::headers::authorization::Bearer;
use poem::web::headers::Authorization;
let username = req
.headers()
.typed_get::<Authorization<Bearer>>()
.and_then(|bearer| parse_user_from_token(bearer.0.token()))
.ok_or_else(|| Error::from_status(StatusCode::UNAUTHORIZED))?;
Ok(User { name: username })
}
} But I prefer to define a struct User {
name: String,
}
#[derive(SecurityScheme)]
#[oai(type = "bearer", checker = "parse_token")]
struct MyUserAuthorization(User);
async fn parse_token(req: &Request, bearer: poem_openapi::auth::Bearer) -> Option<User> {
todo!()
}
#[OpenApi]
impl UserApi {
/// Get Current User
#[oai(path = "/", method = "get")]
async fn get_user(&self, user: MyUserAuthorization) -> Result<PlainText<String>> {
Ok(PlainText(format!("Hi user: {}", user.0.name)))
}
} |
Beta Was this translation helpful? Give feedback.
-
Not yet, maybe in the next version I will let the |
Beta Was this translation helpful? Give feedback.
This is the first way, a custom
Extractor
is used to extract the username fromBearer
.