-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathcallback.ts
More file actions
308 lines (284 loc) · 11.4 KB
/
Copy pathcallback.ts
File metadata and controls
308 lines (284 loc) · 11.4 KB
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
import type {
OAuthConfig,
PersistentSession,
ProviderKeys,
TokenRequest,
TokenRespose,
Tokens,
UserSession,
} from '../../types'
import type { H3Event } from 'h3'
import type { OidcProviderConfig } from '../utils/provider'
import type { JwtPayload } from '../utils/security'
import { useRuntimeConfig } from '#imports'
import { deleteCookie, eventHandler, getQuery, getRequestURL, readBody, sendRedirect } from 'h3'
import { useStorage } from 'nitropack/runtime'
import { normalizeURL, parseURL } from 'ufo'
import * as providerPresets from '../../providers'
import { validateConfig } from '../utils/config'
import { textToBase64 } from '../utils/encoding'
import {
configMerger,
convertObjectToSnakeCase,
convertTokenRequestToType,
oidcErrorHandler,
useOidcLogger,
} from '../utils/oidc'
import { createProviderFetch } from '../utils/provider'
import { resolveCallbackRedirectUrl } from '../utils/redirect'
import { encryptToken, parseJwtToken, validateToken } from '../utils/security'
import { getUserSessionId, setUserSession, useAuthSession } from '../utils/session'
function callbackEventHandler({ onSuccess }: OAuthConfig<UserSession>) {
const logger = useOidcLogger()
return eventHandler(async (event: H3Event) => {
const provider = event.path.split('/')[2] as ProviderKeys
const runtimeProviderConfig = useRuntimeConfig().oidc.providers[provider] as OidcProviderConfig
const config = configMerger(runtimeProviderConfig, providerPresets[provider])
const hasConfiguredCallbackRedirectUrl =
typeof runtimeProviderConfig?.callbackRedirectUrl === 'string'
// Create custom fetch instance for this provider
const customFetch = await createProviderFetch(config)
const validationResult = validateConfig(config, config.requiredProperties)
if (!validationResult.valid) {
logger.error(
`[${provider}] Missing or empty configuration properties:`,
validationResult.missingProperties?.join(', '),
)
return oidcErrorHandler(event, 'Invalid configuration')
}
const session = await useAuthSession(event, config.sessionConfiguration?.maxAuthSessionAge)
const {
code,
state,
id_token,
admin_consent,
error,
error_description,
}: {
code: string
state: string
id_token: string
admin_consent: string
error: string
error_description: string
} = event.method === 'POST' ? await readBody(event) : getQuery(event)
// Check for admin consent callback
if (admin_consent) {
const url = getRequestURL(event)
return sendRedirect(event, `${url.origin}/auth/${provider}/login`, 200)
}
// Verify id_token, if available (hybrid flow)
if (id_token) {
const parsedIdToken = parseJwtToken(id_token)
if (parsedIdToken.nonce !== session.data.nonce) {
return oidcErrorHandler(event, 'Nonce mismatch')
}
}
// Check for valid callback
if (!code || (config.state && !state) || error) {
if (error) {
logger.error(`[${provider}] ${error}`, error_description && `: ${error_description}`)
}
if (!code) {
return oidcErrorHandler(event, 'Callback failed, missing code')
}
return oidcErrorHandler(event, 'Callback failed')
}
// Check for valid state
if (config.state && state !== session.data.state) {
return oidcErrorHandler(event, 'State mismatch')
}
// Construct request header object
const headers: HeadersInit = {}
// Validate if authentication information should be send in header or body
if (config.authenticationScheme === 'header') {
const encodedCredentials = textToBase64(`${config.clientId}:${config.clientSecret}`, {
dataURL: false,
})
headers.authorization = `Basic ${encodedCredentials}`
}
// Construct form data for token request
const requestBody: TokenRequest = {
client_id: config.clientId,
code,
grant_type: config.grantType,
...(config.redirectUri && { redirect_uri: session.data.redirect || config.redirectUri }),
...(config.scopeInTokenRequest && config.scope && { scope: config.scope.join(' ') }),
...(config.pkce && { code_verifier: session.data.codeVerifier }),
...(config.authenticationScheme &&
config.authenticationScheme === 'body' && {
client_secret: normalizeURL(config.clientSecret),
}),
...(config.additionalTokenParameters &&
convertObjectToSnakeCase(config.additionalTokenParameters)),
}
// Make token request
let tokenResponse: TokenRespose
try {
tokenResponse = await customFetch(config.tokenUrl, {
method: 'POST',
headers,
body: convertTokenRequestToType(requestBody, config.tokenRequestType ?? undefined),
})
} catch (error: unknown) {
// Log ofetch error data to console
const fetchError = error as {
data?: { error?: string; error_description?: string; suberror?: string }
}
logger.error(
fetchError?.data
? `${fetchError.data.error}: ${fetchError.data.error_description}`
: String(error),
)
// Handle Microsoft consent_required error
if (fetchError?.data?.suberror === 'consent_required') {
const consentUrl = `https://login.microsoftonline.com/${parseURL(config.authorizationUrl).pathname.split('/')[1]}/adminconsent?client_id=${config.clientId}`
return sendRedirect(event, consentUrl, 302)
}
return oidcErrorHandler(event, 'Token request failed')
}
// Initialize tokens object
let tokens: Tokens
// Validate tokens only if audience is matched
let accessToken: JwtPayload | Record<string, never>
let idToken: JwtPayload | Record<string, never> | undefined
if (!tokenResponse.access_token)
return oidcErrorHandler(event, `[${provider}] No access token found`)
try {
accessToken = parseJwtToken(tokenResponse.access_token, !!config.skipAccessTokenParsing)
idToken = tokenResponse.id_token ? parseJwtToken(tokenResponse.id_token) : undefined
} catch (error) {
return oidcErrorHandler(event, `[${provider}] Token parsing failed: ${String(error)}`)
}
if (
[config.audience as string, config.clientId].some(
(audience) => accessToken.aud?.includes(audience) || idToken?.aud?.includes(audience),
) &&
(config.validateAccessToken || config.validateIdToken)
) {
// Get OIDC configuration
const openIdConfiguration =
config.openIdConfiguration && typeof config.openIdConfiguration === 'object'
? config.openIdConfiguration
: typeof config.openIdConfiguration === 'string'
? await customFetch(config.openIdConfiguration)
: await config.openIdConfiguration!(config)
const validationOptions = {
jwksUri: openIdConfiguration.jwks_uri as string,
...(openIdConfiguration.issuer && { issuer: openIdConfiguration.issuer as string }),
...(config.audience && { audience: [config.audience, config.clientId] }),
}
try {
tokens = {
accessToken: config.validateAccessToken
? await validateToken(tokenResponse.access_token, validationOptions)
: accessToken,
...(tokenResponse.refresh_token && { refreshToken: tokenResponse.refresh_token }),
...(tokenResponse.id_token && {
idToken: config.validateIdToken
? await validateToken(tokenResponse.id_token, validationOptions)
: parseJwtToken(tokenResponse.id_token),
}),
}
} catch (error) {
return oidcErrorHandler(event, `[${provider}] Token validation failed: ${String(error)}`)
}
} else {
logger.info('Skipped token validation')
tokens = {
accessToken,
...(tokenResponse.refresh_token && { refreshToken: tokenResponse.refresh_token }),
...(tokenResponse.id_token && { idToken: parseJwtToken(tokenResponse.id_token) }),
}
}
// Construct user object
const timestamp = Math.trunc(Date.now() / 1000) // Use seconds instead of milliseconds to align with JWT
const user: UserSession = {
canRefresh: !!tokens.refreshToken,
singleSignOut: !!config.sessionConfiguration?.singleSignOut,
loggedInAt: timestamp,
updatedAt: timestamp,
expireAt: tokens.accessToken.exp || timestamp + useRuntimeConfig().oidc.session.maxAge!,
provider,
}
// Request userinfo
try {
if (config.userInfoUrl) {
const userInfoResult = await customFetch(config.userInfoUrl, {
headers: {
Authorization: `${tokenResponse.token_type} ${tokenResponse.access_token}`,
},
})
user.userInfo = config.filterUserInfo
? Object.fromEntries(
Object.entries(userInfoResult).filter(([key]) =>
config.filterUserInfo?.includes(key),
),
)
: userInfoResult
}
} catch (error) {
logger.warn(`[${provider}] Failed to fetch userinfo`, error)
}
// Get user name from access token
if (config.userNameClaim) {
user.userName =
config.userNameClaim in tokens.accessToken
? (tokens.accessToken[config.userNameClaim] as string)
: ''
}
// Get optional claims from id token
if (config.optionalClaims && tokens.idToken) {
const parsedIdToken = tokens.idToken
user.claims = {}
config.optionalClaims.forEach((claim) => {
if (parsedIdToken[claim]) {
;(user.claims as Record<string, unknown>)[claim] = parsedIdToken[claim]
}
})
}
if (tokenResponse.refresh_token || config.exposeAccessToken || config.exposeIdToken) {
const tokenKey = process.env.NUXT_OIDC_TOKEN_KEY as string
const persistentSession: PersistentSession = {
createdAt: new Date(),
updatedAt: new Date(),
exp: accessToken.exp as number,
iat: accessToken.iat as number,
accessToken: await encryptToken(tokenResponse.access_token, tokenKey),
...(tokenResponse.refresh_token && {
refreshToken: await encryptToken(tokenResponse.refresh_token, tokenKey),
}),
...(tokenResponse.id_token && {
idToken: await encryptToken(tokenResponse.id_token, tokenKey),
}),
}
if (
config.sessionConfiguration?.singleSignOut &&
config.sessionConfiguration?.singleSignOutIdField &&
(tokens.accessToken[config.sessionConfiguration.singleSignOutIdField] ||
tokens.idToken?.[config.sessionConfiguration.singleSignOutIdField])
) {
persistentSession.singleSignOutId = tokens.accessToken.sub || tokens.idToken?.sub
}
const userSessionId = await getUserSessionId(event)
await useStorage('oidc').setItem<PersistentSession>(userSessionId, persistentSession)
}
const sessionCallbackRedirectUrl = session.data.callbackRedirectUrl
await session.clear()
deleteCookie(event, 'oidc')
return onSuccess(event, {
user,
callbackRedirectUrl: resolveCallbackRedirectUrl({
configuredCallbackRedirectUrl: config.callbackRedirectUrl,
hasConfiguredCallbackRedirectUrl,
sessionCallbackRedirectUrl,
}),
})
})
}
export default callbackEventHandler({
async onSuccess(event, { user, callbackRedirectUrl }) {
await setUserSession(event, user as UserSession)
return sendRedirect(event, callbackRedirectUrl || ('/' as string))
},
})