actix_web_security/authentication/scheme/
header_extractor.rs

1//! The authorization header trait definition and utility functions.
2
3use actix_web::http::{HeaderMap, HeaderValue};
4use async_trait::async_trait;
5
6use crate::authentication::error::error_type::AuthenticationError;
7use crate::authentication::scheme::authentication::Authentication;
8
9/// The trait of `AuthorizationHeaderExtractor` to be implemented for a specific authentication scheme.
10/// Takes a set of HTTP-Headers from the client request and extracts a token (in form of a boxed `Authentication`) from the headers.
11#[async_trait]
12pub trait AuthorizationHeaderExtractor: Send + Sync {
13    async fn extract_token(
14        &self,
15        request: &HeaderMap,
16    ) -> Result<Box<dyn Authentication>, AuthenticationError>;
17}
18
19/// Utility function to extract the actual token from the header for a given authentication scheme (basic/bearer).
20/// Returns either a `String` with the extracted token (without the scheme prefix from the header) or an `AuthenticationError`.
21pub fn extract_auth_header(
22    header: &HeaderValue,
23    auth_scheme: &str,
24    header_length: usize,
25) -> Result<String, AuthenticationError> {
26    if header.len() < header_length {
27        return Err(AuthenticationError::InvalidAuthorizationHeader);
28    }
29
30    // Split header into scheme (Basic/Bearer) and the actual token
31    let token: &str;
32    if let Ok(header_str) = header.to_str() {
33        let mut parts = header_str.splitn(2, ' ');
34        match parts.next() {
35            Some(scheme) if scheme == auth_scheme => (),
36            _ => return Err(AuthenticationError::InvalidAuthorizationHeader),
37        }
38        token = parts
39            .next()
40            .ok_or(AuthenticationError::InvalidAuthorizationHeader)?
41    } else {
42        return Err(AuthenticationError::InvalidAuthorizationHeader);
43    }
44    Ok(token.to_string())
45}