Skip to main content

actix_security_core/http/security/
http_basic.rs

1//! HTTP Basic Authentication support.
2//!
3//! # Spring Security Equivalent
4//! `org.springframework.security.web.authentication.www.BasicAuthenticationFilter`
5//!
6//! # Feature Flag
7//! Requires the `http-basic` feature (enabled by default).
8
9#[cfg(feature = "http-basic")]
10use actix_web::dev::ServiceRequest;
11#[cfg(feature = "http-basic")]
12use actix_web::http;
13#[cfg(feature = "http-basic")]
14use base64::prelude::*;
15
16#[cfg(feature = "http-basic")]
17use crate::http::security::user::User;
18
19/// Extracts credentials from HTTP Basic Authentication header.
20///
21/// # Spring Security Equivalent
22/// `BasicAuthenticationFilter`
23///
24/// Parses the `Authorization: Basic <base64(username:password)>` header.
25#[cfg(feature = "http-basic")]
26pub fn extract_basic_auth<F>(req: &ServiceRequest, verify: F) -> Option<User>
27where
28    F: FnOnce(&str, &str) -> Option<User>,
29{
30    let auth_header = req.headers().get(http::header::AUTHORIZATION)?;
31    let auth_str = auth_header.to_str().ok()?;
32
33    // Check for "Basic " prefix
34    let credentials = auth_str.strip_prefix("Basic ")?;
35
36    // Decode base64
37    let decoded = BASE64_STANDARD.decode(credentials).ok()?;
38    let decoded_str = String::from_utf8(decoded).ok()?;
39
40    // Split username:password
41    let (username, password) = decoded_str.split_once(':')?;
42
43    verify(username, password)
44}
45
46/// HTTP Basic Authentication configuration.
47///
48/// # Spring Security Equivalent
49/// `HttpSecurity.httpBasic()`
50///
51/// Provides configuration for HTTP Basic authentication including
52/// custom realm names and entry points.
53#[cfg(feature = "http-basic")]
54#[derive(Clone)]
55pub struct HttpBasicConfig {
56    realm: String,
57}
58
59#[cfg(feature = "http-basic")]
60impl HttpBasicConfig {
61    /// Creates a new HTTP Basic configuration with default realm "Restricted".
62    pub fn new() -> Self {
63        HttpBasicConfig {
64            realm: "Restricted".to_string(),
65        }
66    }
67
68    /// Sets the realm name for the WWW-Authenticate header.
69    ///
70    /// # Example
71    /// ```ignore
72    /// let config = HttpBasicConfig::new().realm("MyApplication");
73    /// ```
74    pub fn realm(mut self, realm: &str) -> Self {
75        self.realm = realm.to_string();
76        self
77    }
78
79    /// Creates the WWW-Authenticate header value.
80    pub fn www_authenticate_header(&self) -> String {
81        format!("Basic realm=\"{}\"", self.realm)
82    }
83}
84
85#[cfg(feature = "http-basic")]
86impl Default for HttpBasicConfig {
87    fn default() -> Self {
88        Self::new()
89    }
90}