poem_openapi/auth/
api_key.rs

1use poem::{Request, Result};
2
3use crate::{
4    auth::ApiKeyAuthorization, base::UrlQuery, error::AuthorizationError, registry::MetaParamIn,
5};
6
7/// Used to extract the Api Key from the request.
8#[derive(Debug)]
9pub struct ApiKey {
10    /// Api key
11    pub key: String,
12}
13
14impl ApiKeyAuthorization for ApiKey {
15    fn from_request(
16        req: &Request,
17        query: &UrlQuery,
18        name: &str,
19        in_type: MetaParamIn,
20    ) -> Result<Self> {
21        match in_type {
22            MetaParamIn::Query => query
23                .get(name)
24                .cloned()
25                .map(|value| Self { key: value })
26                .ok_or_else(|| AuthorizationError.into()),
27            MetaParamIn::Header => req
28                .headers()
29                .get(name)
30                .and_then(|value| value.to_str().ok())
31                .map(|value| Self {
32                    key: value.to_string(),
33                })
34                .ok_or_else(|| AuthorizationError.into()),
35            #[cfg(feature = "cookie")]
36            MetaParamIn::Cookie => req
37                .cookie()
38                .get(name)
39                .as_ref()
40                .map(|cookie| Self {
41                    key: cookie.value_str().to_string(),
42                })
43                .ok_or_else(|| AuthorizationError.into()),
44            _ => unreachable!(),
45        }
46    }
47}