actix_web_security/authentication/scheme/bearer/jwt/
authentication_provider.rs1use 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#[derive(Clone)]
14pub struct JwtAuthenticationProvider {
15 user_details_service: Box<dyn JwtUserDetailsService>,
16}
17
18impl JwtAuthenticationProvider {
19 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}