actix_security_core/http/security/
http_basic.rs1#[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#[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 let credentials = auth_str.strip_prefix("Basic ")?;
35
36 let decoded = BASE64_STANDARD.decode(credentials).ok()?;
38 let decoded_str = String::from_utf8(decoded).ok()?;
39
40 let (username, password) = decoded_str.split_once(':')?;
42
43 verify(username, password)
44}
45
46#[cfg(feature = "http-basic")]
54#[derive(Clone)]
55pub struct HttpBasicConfig {
56 realm: String,
57}
58
59#[cfg(feature = "http-basic")]
60impl HttpBasicConfig {
61 pub fn new() -> Self {
63 HttpBasicConfig {
64 realm: "Restricted".to_string(),
65 }
66 }
67
68 pub fn realm(mut self, realm: &str) -> Self {
75 self.realm = realm.to_string();
76 self
77 }
78
79 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}