actix_web_httpauth/headers/authorization/
header.rs

1use std::fmt;
2
3use actix_web::{
4    error::ParseError,
5    http::header::{Header, HeaderName, HeaderValue, TryIntoHeaderValue, AUTHORIZATION},
6    HttpMessage,
7};
8
9use crate::headers::authorization::scheme::Scheme;
10
11/// `Authorization` header, defined in [RFC 7235](https://tools.ietf.org/html/rfc7235#section-4.2)
12///
13/// The "Authorization" header field allows a user agent to authenticate itself with an origin
14/// server—usually, but not necessarily, after receiving a 401 (Unauthorized) response. Its value
15/// consists of credentials containing the authentication information of the user agent for the
16/// realm of the resource being requested.
17///
18/// `Authorization` is generic over an [authentication scheme](Scheme).
19///
20/// # Examples
21/// ```
22/// # use actix_web::{HttpRequest, Result, http::header::Header};
23/// # use actix_web_httpauth::headers::authorization::{Authorization, Basic};
24/// fn handler(req: HttpRequest) -> Result<String> {
25///     let auth = Authorization::<Basic>::parse(&req)?;
26///
27///     Ok(format!("Hello, {}!", auth.as_ref().user_id()))
28/// }
29/// ```
30#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
31pub struct Authorization<S: Scheme>(S);
32
33impl<S: Scheme> Authorization<S> {
34    /// Consumes `Authorization` header and returns inner [`Scheme`] implementation.
35    pub fn into_scheme(self) -> S {
36        self.0
37    }
38}
39
40impl<S: Scheme> From<S> for Authorization<S> {
41    fn from(scheme: S) -> Authorization<S> {
42        Authorization(scheme)
43    }
44}
45
46impl<S: Scheme> AsRef<S> for Authorization<S> {
47    fn as_ref(&self) -> &S {
48        &self.0
49    }
50}
51
52impl<S: Scheme> AsMut<S> for Authorization<S> {
53    fn as_mut(&mut self) -> &mut S {
54        &mut self.0
55    }
56}
57
58impl<S: Scheme> fmt::Display for Authorization<S> {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        fmt::Display::fmt(&self.0, f)
61    }
62}
63
64impl<S: Scheme> Header for Authorization<S> {
65    #[inline]
66    fn name() -> HeaderName {
67        AUTHORIZATION
68    }
69
70    fn parse<T: HttpMessage>(msg: &T) -> Result<Self, ParseError> {
71        let header = msg.headers().get(Self::name()).ok_or(ParseError::Header)?;
72        let scheme = S::parse(header).map_err(|_| ParseError::Header)?;
73
74        Ok(Authorization(scheme))
75    }
76}
77
78impl<S: Scheme> TryIntoHeaderValue for Authorization<S> {
79    type Error = <S as TryIntoHeaderValue>::Error;
80
81    fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
82        self.0.try_into_value()
83    }
84}