actix_web_security/authentication/
mod.rs

1//! The authentication module provides all authentication related functionality.
2//! This consists of the actix middleware, authentication providers and default implementations
3//! for OAuth2 and Basic authentication.
4
5use crate::authentication::error::error_type::AuthenticationError;
6use crate::authentication::scheme::authentication::Authentication;
7use crate::authentication::scheme::authentication_provider::AuthenticationProvider;
8use crate::user_details::UserDetails;
9
10pub mod endpoint_matcher;
11pub mod error;
12pub mod middleware;
13pub mod scheme;
14
15/// A provider manager can be used to register one or more authentication providers to be executed in
16/// a chain (until the authentication on a provider succeeds or fails on all providers).
17/// A provider manager is registered in the middleware to execute the authentication process.
18#[derive(Clone)]
19pub struct ProviderManager {
20    providers: Vec<Box<dyn AuthenticationProvider>>,
21}
22
23impl ProviderManager {
24    /// Constructs a new instance for the given vector of boxed authentication providers.
25    pub fn new(providers: Vec<Box<dyn AuthenticationProvider>>) -> ProviderManager {
26        ProviderManager { providers }
27    }
28
29    #[allow(clippy::borrowed_box)]
30    pub async fn authenticate(
31        &self,
32        authentication: &Box<dyn Authentication>,
33    ) -> Result<Box<dyn UserDetails>, AuthenticationError> {
34        let providers = &self.providers;
35        let mut last_error: Option<AuthenticationError> = None;
36        for provider in providers {
37            let result = provider.authenticate(authentication).await;
38            match result {
39                Ok(user) => return Ok(user),
40                Err(err) => {
41                    last_error = Some(err);
42                    continue;
43                }
44            }
45        }
46        match last_error {
47            Some(e) => Err(e),
48            None => Err(AuthenticationError::UsernameNotFound),
49        }
50    }
51}