@@ -191,7 +191,7 @@ pub struct AuthorizationValidationData {
191191 pub state : String ,
192192
193193 /// A string to mitigate replay attacks.
194- pub nonce : String ,
194+ pub nonce : Option < String > ,
195195
196196 /// The URI where the end-user will be redirected after authorization.
197197 pub redirect_uri : Url ,
@@ -216,7 +216,7 @@ fn build_authorization_request(
216216) -> Result < ( FullAuthorizationRequest , AuthorizationValidationData ) , AuthorizationError > {
217217 let AuthorizationRequestData {
218218 client_id,
219- mut scope,
219+ scope,
220220 redirect_uri,
221221 code_challenge_methods_supported,
222222 display,
@@ -229,9 +229,13 @@ fn build_authorization_request(
229229 response_mode,
230230 } = authorization_data;
231231
232+ let is_openid = scope. contains ( & OPENID ) ;
233+
232234 // Generate a random CSRF "state" token and a nonce.
233235 let state = Alphanumeric . sample_string ( rng, 16 ) ;
234- let nonce = Alphanumeric . sample_string ( rng, 16 ) ;
236+
237+ // Generate a random nonce if we're in 'OpenID Connect' mode
238+ let nonce = is_openid. then ( ||Alphanumeric . sample_string ( rng, 16 ) ) ;
235239
236240 // Use PKCE, whenever possible.
237241 let ( pkce, code_challenge_verifier) = if code_challenge_methods_supported
@@ -263,7 +267,7 @@ fn build_authorization_request(
263267 scope,
264268 state : Some ( state. clone ( ) ) ,
265269 response_mode,
266- nonce : Some ( nonce. clone ( ) ) ,
270+ nonce : nonce. clone ( ) ,
267271 display,
268272 prompt,
269273 max_age,
@@ -440,10 +444,12 @@ pub async fn access_token_with_authorization_code(
440444 . extract_optional_with_options ( & mut claims, TokenHash :: new ( signing_alg, & code) )
441445 . map_err ( IdTokenError :: from) ?;
442446
443- // Nonce must match.
444- claims:: NONCE
445- . extract_required_with_options ( & mut claims, validation_data. nonce . as_str ( ) )
446- . map_err ( IdTokenError :: from) ?;
447+ // Nonce must match if we have one.
448+ if let Some ( nonce) = validation_data. nonce . as_deref ( ) {
449+ claims:: NONCE
450+ . extract_required_with_options ( & mut claims, nonce)
451+ . map_err ( IdTokenError :: from) ?;
452+ }
447453
448454 Some ( id_token. into_owned ( ) )
449455 } else {
0 commit comments