actix_web_security/authentication/scheme/bearer/jwt/
authentication_provider.rs

1//! A default implementation of an `AuthenticationProvider` for a JWT based OAuth2 authentication.
2
3use async_trait::async_trait;
4
5use crate::authentication::error::error_type::AuthenticationError;
6use crate::authentication::scheme::authentication::Authentication;
7use crate::authentication::scheme::authentication_provider::AuthenticationProvider;
8use crate::authentication::scheme::bearer::jwt::user_details_service::JwtUserDetailsService;
9use crate::authentication::scheme::bearer::jwt::JwtBearerAuthentication;
10use crate::user_details::UserDetails;
11
12/// The definition of a `JwtAuthenticationProvider`.
13#[derive(Clone)]
14pub struct JwtAuthenticationProvider {
15    user_details_service: Box<dyn JwtUserDetailsService>,
16}
17
18impl JwtAuthenticationProvider {
19    /// Constructs an instance of a `JwtAuthenticationProvider` for a boxed instance of a `JwtUserDetailsService`
20    /// which does the actual data lookup for the authentication.
21    pub fn new(user_details_service: Box<dyn JwtUserDetailsService>) -> JwtAuthenticationProvider {
22        JwtAuthenticationProvider {
23            user_details_service,
24        }
25    }
26}
27
28#[async_trait]
29impl AuthenticationProvider for JwtAuthenticationProvider {
30    #[allow(clippy::borrowed_box)]
31    async fn authenticate(
32        &self,
33        authentication: &Box<dyn Authentication>,
34    ) -> Result<Box<dyn UserDetails>, AuthenticationError> {
35        if authentication.is::<JwtBearerAuthentication>() {
36            let jwt_auth = authentication
37                .downcast_ref::<JwtBearerAuthentication>()
38                .unwrap();
39            match self.user_details_service.find_user(&jwt_auth.token).await {
40                Some(user) => Ok(user),
41                None => Err(AuthenticationError::UsernameNotFound),
42            }
43        } else {
44            Err(AuthenticationError::InvalidAuthentication)
45        }
46    }
47}