Skip to main content

light_openid/
client.rs

1//! # Open ID client implementation
2
3use crate::code_challenge::{CodeChallenge, CodeChallengeVerifier};
4use crate::errors::{OpenIdError, Res};
5use crate::nonce::Nonce;
6use crate::primitives::{
7    AuthorizeQuery, OpenIDConfig, OpenIDToken, OpenIDTokenResponse, OpenIDUserInfo,
8};
9use crate::utils::http_client;
10use jsonwebtoken::{DecodingKey, TokenData, Validation};
11use serde::de::DeserializeOwned;
12use std::collections::{HashMap, HashSet};
13use std::fmt::Display;
14use zeroize::Zeroizing;
15
16/// OpenID client options
17#[derive(Debug, Clone)]
18pub struct OpenIDClientOpts {
19    /// This client ID
20    pub client_id: String,
21    /// This client secret
22    pub client_secret: Option<Zeroizing<String>>,
23    /// Redirect URI to use when performing authentication requests
24    pub redirect_uri: String,
25    /// Disable id token signature & content check
26    pub validate_id_token_sig: bool,
27    /// Accepted audiences in JWT
28    pub accepted_audiences: Vec<String>,
29    /// Whether audience field of jwt should be validated or not
30    pub validate_aud: bool,
31    /// Whether expiration field of jwt should be validated or not
32    pub validate_exp: bool,
33    /// Whether not before field of jwt should be validated or not
34    pub validate_nbf: bool,
35}
36
37impl OpenIDClientOpts {
38    pub fn new(
39        client_id: impl Display,
40        client_secret: Option<&str>,
41        redirect_uri: impl Display,
42    ) -> Self {
43        Self {
44            client_id: client_id.to_string(),
45            client_secret: client_secret.map(|s| Zeroizing::new(s.to_string())),
46            redirect_uri: redirect_uri.to_string(),
47            accepted_audiences: vec![client_id.to_string()],
48            validate_id_token_sig: true,
49            validate_aud: true,
50            validate_exp: true,
51            validate_nbf: false,
52        }
53    }
54}
55
56enum TokenEndpointAuth<'a> {
57    AuthorizationCode(&'a str),
58    RefreshToken(&'a str),
59}
60
61/// OpenID client
62#[derive(Clone)]
63pub struct OpenIDClient {
64    pub config: OpenIDConfig,
65    pub jwks: Option<jsonwebtoken::jwk::JwkSet>,
66    pub opts: OpenIDClientOpts,
67}
68
69impl OpenIDClient {
70    /// Construct an OpenID client by give hard-coded configuration values
71    pub async fn new(
72        config: OpenIDConfig,
73        jwks: Option<jsonwebtoken::jwk::JwkSet>,
74        opts: &OpenIDClientOpts,
75    ) -> Self {
76        Self {
77            config,
78            jwks,
79            opts: opts.clone(),
80        }
81    }
82
83    /// Construct an OpenID client by loading configuration from a given
84    /// .well-known/openid-configuration URL
85    #[tracing::instrument(skip(opts))]
86    pub async fn new_from_url(url: &str, opts: &OpenIDClientOpts) -> Res<Self> {
87        let config = http_client::get_json_request(url).await?;
88
89        let mut client = Self {
90            config,
91            jwks: None,
92            opts: opts.clone(),
93        };
94
95        if opts.validate_id_token_sig {
96            client.jwks = Some(http_client::get_json_request(&client.config.jwks_uri).await?)
97        }
98
99        Ok(client)
100    }
101
102    /// Get the authorization URL where a user should be redirect to perform authentication
103    #[tracing::instrument(skip(self, state))]
104    pub fn gen_authorization_url(
105        &self,
106        state: &str,
107        code_challenge: Option<CodeChallenge>,
108        nonce: Option<&Nonce>,
109    ) -> Res<String> {
110        let query = AuthorizeQuery {
111            response_type: "code".into(),
112            scope: "openid profile email".into(),
113            client_id: self.opts.client_id.as_str().into(),
114            redirect_uri: self.opts.redirect_uri.as_str().into(),
115            state: Some(state.into()),
116            response_mode: None,
117            nonce: nonce.map(|n| n.hash().into()),
118            code_challenge: code_challenge
119                .as_ref()
120                .map(|c| c.code_challenge.as_str().into()),
121            code_challenge_method: code_challenge
122                .as_ref()
123                .map(|c| c.code_challenge_method.as_str().into()),
124        };
125
126        Ok(format!(
127            "{}?{}",
128            self.config.authorization_endpoint,
129            serde_qs::to_string(&query).map_err(OpenIdError::EncodeAuthorizationUrlQuery)?
130        ))
131    }
132
133    /// Query the token endpoint using an authorization code
134    #[tracing::instrument(skip(self, code, code_verifier))]
135    pub async fn request_token_from_code(
136        &self,
137        code: &str,
138        code_verifier: Option<&CodeChallengeVerifier>,
139        nonce: Option<&Nonce>,
140    ) -> Res<(OpenIDTokenResponse, String)> {
141        self.request_token(
142            &TokenEndpointAuth::AuthorizationCode(code),
143            code_verifier,
144            nonce,
145        )
146        .await
147    }
148
149    /// Query the token endpoint using a refresh token
150    #[tracing::instrument(skip(self, refresh_token))]
151    pub async fn request_token_from_refresh_token(
152        &self,
153        refresh_token: &str,
154    ) -> Res<(OpenIDTokenResponse, String)> {
155        self.request_token(&TokenEndpointAuth::RefreshToken(refresh_token), None, None)
156            .await
157    }
158
159    /// Query the token endpoint
160    ///
161    /// This endpoint returns both the parsed and the raw response, to allow handling
162    /// of bonus fields
163    async fn request_token(
164        &self,
165        auth: &TokenEndpointAuth<'_>,
166        code_verifier: Option<&CodeChallengeVerifier>,
167        nonce: Option<&Nonce>,
168    ) -> Res<(OpenIDTokenResponse, String)> {
169        let mut params = HashMap::new();
170        match auth {
171            TokenEndpointAuth::AuthorizationCode(code) => {
172                params.insert("grant_type", "authorization_code");
173                params.insert("code", code);
174            }
175            TokenEndpointAuth::RefreshToken(token) => {
176                params.insert("grant_type", "refresh_token");
177                params.insert("refresh_token", token);
178            }
179        }
180        if let Some(verifier) = code_verifier {
181            params.insert("code_verifier", &verifier.0);
182        }
183        params.insert("redirect_uri", self.opts.redirect_uri.as_str());
184
185        let response = http_client::send_request(
186            reqwest::Client::new()
187                .post(&self.config.token_endpoint)
188                .basic_auth(&self.opts.client_id, self.opts.client_secret.as_deref())
189                .form(&params),
190        )
191        .await?
192        .text()
193        .await?;
194
195        let token: OpenIDTokenResponse = serde_json::from_str(&response)?;
196
197        // Check id token signature
198        if self.opts.validate_id_token_sig
199            && self.jwks.is_some()
200            && let Some(id_token) = &token.id_token
201        {
202            let id_token = self
203                .verify_jwt::<OpenIDToken>(id_token)
204                .map_err(|e| OpenIdError::ValidateIdToken(Box::new(e)))?;
205
206            // Validate provided nonce
207            if let Some(nonce) = nonce {
208                let Some(provided_nonce) = id_token.claims.nonce else {
209                    return Err(OpenIdError::MissingNonceInIdToken);
210                };
211
212                if provided_nonce != nonce.hash() {
213                    return Err(OpenIdError::InvalidNonceInIdToken);
214                }
215            }
216        }
217
218        Ok((token, response))
219    }
220
221    /// Decode & verify a JWT signature
222    pub fn verify_jwt<T: DeserializeOwned>(&self, jwt: &str) -> Res<TokenData<T>> {
223        let header = jsonwebtoken::decode_header(jwt).map_err(OpenIdError::DecodeJWTHeader)?;
224
225        let Some(kid) = header.kid else {
226            return Err(OpenIdError::KidRequiredForSignatureVerification);
227        };
228
229        let Some(jwks) = &self.jwks else {
230            return Err(OpenIdError::MissingJWKs);
231        };
232
233        let Some(jwk) = jwks.find(&kid) else {
234            return Err(OpenIdError::UnknownKid(kid));
235        };
236
237        let decoding_key = DecodingKey::from_jwk(jwk).map_err(OpenIdError::DecodeJWK)?;
238
239        let mut validation = Validation::new(header.alg);
240        validation.validate_aud = true;
241        validation.aud = Some(HashSet::from_iter(
242            self.opts.accepted_audiences.iter().cloned(),
243        ));
244        validation.validate_aud = self.opts.validate_aud;
245        validation.validate_exp = self.opts.validate_exp;
246        validation.validate_nbf = self.opts.validate_nbf;
247
248        jsonwebtoken::decode(jwt, &decoding_key, &validation).map_err(OpenIdError::ValidateJWT)
249    }
250
251    /// Query the UserInfo endpoint.
252    ///
253    /// This endpoint should be used after having successfully retrieved the token
254    ///
255    /// This endpoint returns both the parsed value and the raw response, in case of presence
256    /// of additional fields
257    #[tracing::instrument(skip(self, token))]
258    pub async fn request_user_info(
259        &self,
260        token: &OpenIDTokenResponse,
261    ) -> Res<(OpenIDUserInfo, String)> {
262        let response = http_client::send_request(
263            reqwest::Client::new()
264                .get(self.config.userinfo_endpoint.as_ref().expect(
265                    "This client only support information retrieval through userinfo endpoint!",
266                ))
267                .header("Authorization", format!("Bearer {}", token.access_token)),
268        )
269        .await?
270        .text()
271        .await?;
272
273        Ok((serde_json::from_str(&response)?, response))
274    }
275}