tower_oauth2_resource_server/authorizer/
token_authorizer.rs

1use std::sync::Arc;
2
3use log::info;
4use serde::de::DeserializeOwned;
5
6use crate::{
7    authorizer::{
8        jwks::{JwksConsumer, TimerJwksProducer},
9        jwt_validate::OnlyJwtValidator,
10    },
11    error::{AuthError, StartupError},
12    jwt_unverified::UnverifiedJwt,
13    tenant::TenantConfiguration,
14};
15
16use super::{jwks::JwksProducer, jwt_validate::JwtValidator};
17
18#[derive(Clone)]
19pub struct Authorizer<Claims> {
20    identifier: String,
21    jwt_validator: Arc<dyn JwtValidator<Claims> + Send + Sync>,
22}
23
24impl<Claims> Authorizer<Claims>
25where
26    Claims: Clone + DeserializeOwned + Send + Sync + 'static,
27{
28    pub(crate) async fn new(config: TenantConfiguration) -> Result<Self, StartupError> {
29        info!(
30            "Authorizer '{}' will validate the following claims: {}",
31            &config.identifier, &config.claims_validation_spec
32        );
33
34        let validator = Arc::new(OnlyJwtValidator::new(config.claims_validation_spec));
35
36        match config.kind {
37            crate::tenant::TenantKind::JwksUrl {
38                jwks_url,
39                jwks_refresh_interval,
40            } => {
41                let mut jwks_producer = TimerJwksProducer::new(jwks_url, jwks_refresh_interval);
42                jwks_producer.add_consumer(validator.clone());
43                jwks_producer.start();
44            }
45            crate::tenant::TenantKind::Static { jwks } => {
46                validator.receive_jwks(jwks).await;
47            }
48        };
49
50        Ok(Self {
51            identifier: config.identifier,
52            jwt_validator: validator,
53        })
54    }
55}
56
57impl<Claims> Authorizer<Claims> {
58    pub fn identifier(&self) -> &str {
59        &self.identifier
60    }
61
62    pub fn has_kid(&self, kid: &str) -> bool {
63        self.jwt_validator.has_kid(kid)
64    }
65}
66
67impl<Claims> Authorizer<Claims>
68where
69    Claims: DeserializeOwned,
70{
71    pub(crate) fn validate(&self, token: &UnverifiedJwt) -> Result<Claims, AuthError> {
72        self.jwt_validator.validate(token)
73    }
74}