Skip to content

Commit df5ffbf

Browse files
committed
feat: add pkce verifier
1 parent 4f4beb9 commit df5ffbf

File tree

2 files changed

+17
-6
lines changed

2 files changed

+17
-6
lines changed

backend/src/oidc/oidcflow.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ use rocket::serde::json::serde_json;
66

77
use openidconnect::{
88
AccessToken, AdditionalClaims, AuthenticationFlow, Client, ClientId, ClientSecret, CsrfToken,
9-
IdToken, IssuerUrl, Nonce, RedirectUrl, Scope, UserInfoClaims,
9+
IdToken, IssuerUrl, Nonce, PkceCodeChallenge, PkceCodeVerifier, RedirectUrl, Scope,
10+
UserInfoClaims,
1011
};
1112

1213
use openidconnect::core::{
@@ -68,11 +69,13 @@ type OidcAppClient = Client<
6869
>;
6970

7071
// Basic data used by the OIDC Client
72+
7173
pub struct OidcFlow {
7274
pub client: OidcAppClient,
7375
pub auth_url: url::Url,
7476
pub csrf_state: CsrfToken,
7577
pub nonce: Nonce,
78+
pub pkce_verifier_secret: String,
7679
}
7780

7881
// OIDC Session cookie stores OIDC tokens and additional information, such as roles, in a cookie.
@@ -171,14 +174,15 @@ impl OidcFlow {
171174
for scope in scopes {
172175
authorize_url = authorize_url.add_scope(Scope::new(scope));
173176
}
174-
let (auth_url, csrf_state, nonce) = authorize_url
175-
// This example is requesting access to the the user's profile including email.
176-
.url();
177+
// Generate a PKCE challenge.
178+
let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
179+
let (auth_url, csrf_state, nonce) = authorize_url.url();
177180
Ok(OidcFlow {
178181
client,
179182
auth_url,
180183
csrf_state,
181184
nonce,
185+
pkce_verifier_secret: pkce_verifier.into_secret(),
182186
})
183187
}
184188
}

backend/src/oidc/routes.rs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
use std::collections::HashMap;
44
use std::path::PathBuf;
55

6-
use openidconnect::{AuthorizationCode, OAuth2TokenResponse, TokenResponse, reqwest};
6+
use openidconnect::{
7+
AuthorizationCode, OAuth2TokenResponse, PkceCodeVerifier, TokenResponse, reqwest,
8+
};
79
use rocket::http::{Cookie, SameSite};
810
use rocket::serde::json::serde_json;
911
use rocket::{State, http::CookieJar, response::Redirect};
@@ -70,7 +72,12 @@ pub async fn oidc_redirect(
7072
// exchange token
7173
let code = AuthorizationCode::new(params.code);
7274
let token_response = match oidc.client.exchange_code(code) {
73-
Ok(code) => match code.request_async(&http_client).await {
75+
Ok(code) => match code
76+
// Set the PKCE code verifier.
77+
.set_pkce_verifier(PkceCodeVerifier::new(oidc.pkce_verifier_secret.clone()))
78+
.request_async(&http_client)
79+
.await
80+
{
7481
Ok(token_response) => token_response,
7582
Err(err) => {
7683
handle_error(&err, "Cannot exchange code");

0 commit comments

Comments
 (0)