1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use std::{collections::HashMap, sync::Arc};
use async_trait::async_trait;
use better_auth_core::{AuthError, AuthRequest, AuthResult, FieldValue};
use indexmap::IndexMap;
use reqwest::header::HeaderMap;
use serde_json::Value;
use super::token::{TokenEndpointAuth, TokenEndpointSecretAuthentication};
use super::{OAuthTokenSet, OAuthUserInfoRequest};
/// Authorization-code exchange values passed to a custom token handler.
pub struct OAuthCodeExchange<'a> {
/// Authorization code returned by the provider.
pub code: &'a str,
/// Callback URI sent to the provider.
pub redirect_uri: &'a str,
/// PKCE verifier persisted with the authorization request.
pub code_verifier: Option<&'a str>,
/// Provider-specific device identifier from the callback.
pub device_id: Option<&'a str>,
}
/// Exchanges a code when a provider does not use a standard token endpoint.
#[async_trait]
pub trait OAuthTokenHandler: Send + Sync {
/// Exchange the authorization code without creating a local session.
async fn get_token(&self, _request: OAuthCodeExchange<'_>) -> AuthResult<OAuthTokenSet> {
Err(AuthError::internal(
"This OAuth token handler does not implement the typed callback",
))
}
/// Return the original token value before expiry defaults, truthiness checks, or object spread.
/// The default invokes the typed callback only for a string or absent verifier.
async fn get_token_native(&self, request: &FieldValue) -> AuthResult<FieldValue> {
let code = request.model_property("code")?;
let redirect_uri = request.model_property("redirectURI")?;
let verifier = request.model_property("codeVerifier")?;
let device = request.model_property("deviceId")?;
let code_verifier = match &verifier {
FieldValue::Undefined => None,
FieldValue::String(value) => Some(value.as_str()),
_ => {
return Err(AuthError::type_error(
"The typed OAuth token callback requires a string or undefined code verifier",
));
}
};
let device_id = match &device {
FieldValue::Undefined => None,
FieldValue::String(value) => Some(value.as_str()),
_ => {
return Err(AuthError::type_error(
"The typed OAuth token callback requires a string or undefined device identifier",
));
}
};
Ok(self
.get_token(OAuthCodeExchange {
code: code.as_str().ok_or_else(|| {
AuthError::type_error(
"The typed OAuth token callback requires a string authorization code",
)
})?,
redirect_uri: redirect_uri.as_str().ok_or_else(|| {
AuthError::type_error(
"The typed OAuth token callback requires a string redirect URI",
)
})?,
code_verifier,
device_id,
})
.await?
.fields()
.into())
}
}
/// Borrowed claims from the configured OIDC signature and claim validation.
pub struct VerifiedOAuthClaims<'a> {
claims: &'a Value,
}
impl<'a> VerifiedOAuthClaims<'a> {
pub(super) fn new(claims: &'a Value) -> Self {
Self { claims }
}
/// Read the claims returned by the configured OIDC signature and claim validation.
pub fn as_value(&self) -> &'a Value {
self.claims
}
}
/// Borrowed runtime inputs for a Generic OAuth profile lookup.
pub struct GenericOAuthProfileContext<'a> {
client_id: &'a str,
expected_nonce: Option<&'a str>,
user_info_url: Option<&'a str>,
verified_claims: Option<VerifiedOAuthClaims<'a>>,
}
impl<'a> GenericOAuthProfileContext<'a> {
pub(super) fn new(
config: &'a GenericOAuthConfig,
expected_nonce: Option<&'a str>,
verified_claims: Option<&'a Value>,
) -> Self {
Self {
client_id: &config.client_id,
expected_nonce,
user_info_url: config.user_info_url.as_deref(),
verified_claims: verified_claims.map(VerifiedOAuthClaims::new),
}
}
/// Read the client identifier from the resolved provider configuration.
pub fn client_id(&self) -> &'a str {
self.client_id
}
/// Read the nonce bound to this flow, when the caller supplied one.
pub fn expected_nonce(&self) -> Option<&'a str> {
self.expected_nonce
}
/// Read the resolved userinfo endpoint.
pub fn user_info_url(&self) -> Option<&'a str> {
self.user_info_url
}
/// Read claims that passed the configured OIDC signature and claim validation.
pub fn verified_claims(&self) -> Option<&VerifiedOAuthClaims<'a>> {
self.verified_claims.as_ref()
}
}
/// Fetches the raw profile used for Generic OAuth account recognition.
#[async_trait]
pub trait GenericOAuthUserInfoHandler: Send + Sync {
/// Return a raw profile at the legacy JSON callback boundary.
/// Native handlers may implement `get_user_info_native` instead.
async fn get_user_info(&self, _tokens: &OAuthUserInfoRequest) -> AuthResult<Option<Value>> {
Err(AuthError::internal(
"This Generic OAuth user info handler does not implement the typed JSON callback",
))
}
/// Read resolved options and completed verification before mapping a profile.
/// Existing handlers retain their token-based lookup unless they override this method.
async fn get_user_info_with_context(
&self,
tokens: &OAuthUserInfoRequest,
_context: GenericOAuthProfileContext<'_>,
) -> AuthResult<Option<Value>> {
self.get_user_info(tokens).await
}
/// Return the original profile, including primitives, null, undefined, and shared objects.
/// The default imports the legacy context-aware callback's JSON result once.
async fn get_user_info_native(
&self,
tokens: &OAuthUserInfoRequest,
context: GenericOAuthProfileContext<'_>,
) -> AuthResult<FieldValue> {
Ok(self
.get_user_info_with_context(tokens, context)
.await?
.map_or(FieldValue::Undefined, FieldValue::from))
}
}
/// Local profile fields; provider account identity is resolved separately.
#[derive(Debug, Clone, Default)]
pub struct OAuthProfile {
/// Application user fields supplied by the profile mapper.
pub additional_fields: better_auth_core::FieldMap,
/// Leave the email unchanged with `None`, or override its string/null/undefined value.
pub email: Option<better_auth_core::SchemaValue<Option<String>>>,
/// Leave the name unchanged with `None`, or override its string/null/undefined value.
pub name: Option<better_auth_core::SchemaValue<Option<String>>>,
/// Override the profile image; `Some(None)` clears the provider value.
pub image: Option<Option<String>>,
/// Leave verification unchanged with `None`, or override its boolean/null/undefined value.
pub email_verified: Option<better_auth_core::SchemaValue<Option<bool>>>,
}
/// Maps provider profile fields without changing the provider account subject.
#[async_trait]
pub trait OAuthProfileMapper: Send + Sync {
/// Return local user fields at the legacy JSON callback boundary.
/// Native mappers may implement `map_profile_native` instead.
async fn map_profile(&self, _profile: &Value) -> AuthResult<OAuthProfile> {
Err(AuthError::internal(
"This OAuth profile mapper does not implement the typed JSON callback",
))
}
/// Read the original profile and return the value spread into the provider user.
/// The default explicitly projects JSON for the legacy callback and consumes its typed patch.
async fn map_profile_native(&self, profile: &FieldValue) -> AuthResult<FieldValue> {
let profile = super::providers::json_profile_bridge(profile)?;
Ok(self.map_profile(&profile).await?.into_native())
}
}
/// Resolves a stable provider account identifier from the original profile.
#[async_trait]
pub trait OAuthAccountSubject: Send + Sync {
/// Return a nonempty immutable identifier; mapped local fields are not supplied.
/// Code flows supply the original token exchange record, before callback metadata is added.
/// Direct ID-token flows supply the endpoint's token record.
async fn resolve_subject(
&self,
_tokens: &OAuthUserInfoRequest,
_profile: &Value,
) -> AuthResult<String> {
Err(AuthError::internal(
"This OAuth account subject resolver does not implement the typed JSON callback",
))
}
/// Return the account subject before the shared JavaScript String conversion and validation.
/// Native resolvers receive the original token value without reading its properties.
/// The default projects the token fields and profile JSON at the legacy callback boundary.
async fn resolve_subject_native(
&self,
tokens: &FieldValue,
profile: &FieldValue,
) -> AuthResult<FieldValue> {
let tokens = OAuthUserInfoRequest::from_fields(tokens.enumerable_fields()?);
let profile = super::providers::json_profile_bridge(profile)?;
Ok(self.resolve_subject(&tokens, &profile).await?.into())
}
}
/// Resolves extra token refresh parameters for the authenticated request.
#[async_trait]
pub trait OAuthRefreshParameters: Send + Sync {
/// Validate request-derived tenant or scope values before returning parameters.
async fn parameters(&self, request: &AuthRequest) -> AuthResult<HashMap<String, String>>;
}
/// Static or request-dependent parameters for a token refresh.
#[derive(Clone)]
pub enum RefreshTokenParameters {
/// Parameters shared by every refresh request.
Static(HashMap<String, String>),
/// Parameters computed from the authenticated request.
Dynamic(Arc<dyn OAuthRefreshParameters>),
}
/// Generic OAuth and OpenID Connect provider configuration.
///
/// Discovery resolves once when the auth instance is built. Set
/// `require_id_token_verification` for providers whose identity comes from ID tokens.
#[derive(Clone)]
pub struct GenericOAuthConfig {
/// OAuth client identifier.
pub client_id: String,
/// Client secret; omit for public clients or private-key JWT authentication.
pub client_secret: Option<String>,
/// OpenID configuration URL.
pub discovery_url: Option<String>,
/// Headers included in the discovery request.
pub discovery_headers: HeaderMap,
/// Require discovery to supply a usable issuer and JWKS URI.
pub require_id_token_verification: bool,
/// Explicit authorization endpoint; overrides discovery.
pub authorization_url: Option<String>,
/// Explicit token endpoint; overrides discovery.
pub token_url: Option<String>,
/// Explicit userinfo endpoint; overrides discovery.
pub user_info_url: Option<String>,
/// Explicit RP-initiated logout endpoint; overrides discovery.
pub end_session_endpoint: Option<String>,
/// Default redirect after provider logout.
pub post_logout_redirect_uri: Option<String>,
/// Complete only local logout even when the provider supports logout.
pub disable_provider_logout: bool,
/// Client authentication for code exchange and token refresh.
pub token_endpoint_auth: Option<TokenEndpointAuth>,
/// Upstream's legacy secret authentication selection.
pub authentication: Option<TokenEndpointSecretAuthentication>,
/// Default scopes; OIDC discovery providers also request `openid`.
pub scopes: Vec<String>,
/// Override the generated callback URI.
pub redirect_uri: Option<String>,
/// Authorization response type; defaults to `code`.
pub response_type: Option<String>,
/// Authorization response mode, such as `query` or `form_post`.
pub response_mode: Option<String>,
/// Provider authentication prompt.
pub prompt: Option<String>,
/// Send PKCE challenges and verifiers; defaults to true.
pub pkce: bool,
/// Authorization access type, such as `offline`.
pub access_type: Option<String>,
/// Fallback access-token lifetime when the token response omits an expiry.
pub access_token_expires_in: Option<f64>,
/// Extra authorization parameters in insertion order; reserved fields are protected.
pub authorization_url_params: IndexMap<String, String>,
/// Extra code-exchange parameters that cannot replace standard grant fields.
pub token_url_params: HashMap<String, String>,
/// Additional headers for authorization-code exchange.
pub authorization_headers: HeaderMap,
/// Extra token refresh parameters.
pub refresh_token_params: Option<RefreshTokenParameters>,
/// Custom code exchange for providers with a nonstandard token endpoint.
pub get_token: Option<Arc<dyn OAuthTokenHandler>>,
/// Custom raw-profile lookup.
pub get_user_info: Option<Arc<dyn GenericOAuthUserInfoHandler>>,
/// Map profile fields independently of account recognition.
pub map_profile_to_user: Option<Arc<dyn OAuthProfileMapper>>,
/// Override the immutable subject resolver (`sub` for OIDC, `id` for OAuth).
pub account_subject: Option<Arc<dyn OAuthAccountSubject>>,
/// Require an explicit `requestSignUp` to create a new user. Omission remains distinct from false.
pub disable_implicit_sign_up: Option<bool>,
/// Reject creation of new users through this provider. Omission remains distinct from false.
pub disable_sign_up: Option<bool>,
/// Update existing local profile fields on sign-in.
pub override_user_info: bool,
/// Require the local user's email to be verified before issuing a session.
pub require_email_verification: bool,
/// Restart callbacks without state using a fresh authorization request.
pub allow_idp_initiated: bool,
/// Disable the default OIDC nonce binding for providers that cannot echo a nonce.
pub disable_id_token_nonce_binding: bool,
}
impl Default for GenericOAuthConfig {
fn default() -> Self {
Self {
client_id: String::new(),
client_secret: None,
discovery_url: None,
discovery_headers: HeaderMap::new(),
require_id_token_verification: false,
authorization_url: None,
token_url: None,
user_info_url: None,
end_session_endpoint: None,
post_logout_redirect_uri: None,
disable_provider_logout: false,
token_endpoint_auth: None,
authentication: None,
scopes: Vec::new(),
redirect_uri: None,
response_type: None,
response_mode: None,
prompt: None,
pkce: true,
access_type: None,
access_token_expires_in: None,
authorization_url_params: IndexMap::new(),
token_url_params: HashMap::new(),
authorization_headers: HeaderMap::new(),
refresh_token_params: None,
get_token: None,
get_user_info: None,
map_profile_to_user: None,
account_subject: None,
disable_implicit_sign_up: None,
disable_sign_up: None,
override_user_info: false,
require_email_verification: false,
allow_idp_initiated: false,
disable_id_token_nonce_binding: false,
}
}
}
impl GenericOAuthConfig {
/// Configure Auth0 discovery from a domain or URL and the default OIDC scopes.
pub fn auth0(client_id: &str, client_secret: &str, domain: &str) -> AuthResult<Self> {
let address = if domain.starts_with("http://") || domain.starts_with("https://") {
domain.to_owned()
} else {
format!("https://{domain}")
};
let url = url::Url::parse(&address)
.map_err(|error| better_auth_core::AuthError::config(error.to_string()))?;
let host = &url[url::Position::BeforeHost..url::Position::AfterPort];
Ok(Self::discovery_preset(
client_id,
client_secret,
format!("https://{host}/.well-known/openid-configuration"),
))
}
/// Configure Keycloak discovery from the realm issuer and default OIDC scopes.
pub fn keycloak(client_id: &str, client_secret: &str, issuer: &str) -> Self {
Self::discovery_preset(
client_id,
client_secret,
format!(
"{}/.well-known/openid-configuration",
issuer.strip_suffix('/').unwrap_or(issuer)
),
)
}
/// Configure Okta discovery from the issuer and default OIDC scopes.
pub fn okta(client_id: &str, client_secret: &str, issuer: &str) -> Self {
Self::keycloak(client_id, client_secret, issuer)
}
fn discovery_preset(client_id: &str, client_secret: &str, discovery_url: String) -> Self {
Self {
client_id: client_id.into(),
client_secret: Some(client_secret.into()),
discovery_url: Some(discovery_url),
scopes: vec!["openid".into(), "profile".into(), "email".into()],
..Default::default()
}
}
}