amqp_api_server/config/
token_validator_config.rs1use jsonwebtoken::jwk::JwkSet;
2
3use crate::error::{Error, ErrorKind};
4
5use super::openid_connect_config::OpenIdConnectConfig;
6
7pub struct TokenValidatorConfig {
8 jwks: JwkSet,
9 openid_connect: OpenIdConnectConfig,
10}
11
12impl TokenValidatorConfig {
13 pub fn new(jwks: JwkSet, openid_connect: OpenIdConnectConfig) -> TokenValidatorConfig {
14 TokenValidatorConfig {
15 jwks,
16 openid_connect,
17 }
18 }
19
20 pub fn jwks(&self) -> &JwkSet {
21 &self.jwks
22 }
23
24 pub fn open_id_connect(&self) -> &OpenIdConnectConfig {
25 &self.openid_connect
26 }
27}
28
29pub async fn try_generate_config(openid_connect: OpenIdConnectConfig) -> Result<TokenValidatorConfig, Error> {
30 let jwks = match try_get_jwks(openid_connect.jwks_uri()).await {
31 Ok(jwks) => jwks,
32 Err(error) => return Err(error),
33 };
34
35 Ok(TokenValidatorConfig {
36 jwks,
37 openid_connect,
38 })
39}
40
41async fn try_get_jwks(jwks_uri: &str) -> Result<JwkSet, Error> {
42 let jwks = match reqwest::get(jwks_uri).await {
43 Ok(response) => match response.json::<JwkSet>().await {
44 Ok(jwks) => jwks,
45 Err(error) => {
46 return Err(Error::new(
47 ErrorKind::AutoConfigFailure,
48 format!("failed to deserialize response as JwkSet: {}", error),
49 ));
50 }
51 },
52 Err(error) => {
53 return Err(Error::new(
54 ErrorKind::AutoConfigFailure,
55 format!("failed to request jwks: {}", error),
56 ));
57 }
58 };
59
60 Ok(jwks)
61}