|
| 1 | +import type { H3Event } from 'h3' |
| 2 | +import { eventHandler, getQuery, sendRedirect } from 'h3' |
| 3 | +import { withQuery } from 'ufo' |
| 4 | +import { defu } from 'defu' |
| 5 | +import { handleMissingConfiguration, handleAccessTokenErrorResponse, getOAuthRedirectURL, requestAccessToken, handlePkceVerifier, handleState, handleInvalidState } from '../utils' |
| 6 | +import { useRuntimeConfig, createError } from '#imports' |
| 7 | +import type { OAuthConfig } from '#auth-utils' |
| 8 | + |
| 9 | +export interface OAuthAzureB2CConfig { |
| 10 | + /** |
| 11 | + * Azure OAuth Client ID |
| 12 | + * @default process.env.NUXT_OAUTH_AZUREB2C_CLIENT_ID |
| 13 | + */ |
| 14 | + clientId?: string |
| 15 | + /** |
| 16 | + * Azure OAuth Policy |
| 17 | + * @default process.env.NUXT_OAUTH_AZUREB2C_POLICY |
| 18 | + */ |
| 19 | + policy?: string |
| 20 | + /** |
| 21 | + * Azure OAuth Tenant ID |
| 22 | + * @default process.env.NUXT_OAUTH_AZUREB2C_TENANT |
| 23 | + */ |
| 24 | + tenant?: string |
| 25 | + /** |
| 26 | + * Azure OAuth Scope |
| 27 | + * @default ['offline_access'] |
| 28 | + * @see https://learn.microsoft.com/en-us/azure/active-directory-b2c/access-tokens#scopes |
| 29 | + */ |
| 30 | + scope?: string[] |
| 31 | + /** |
| 32 | + * Azure OAuth Authorization URL |
| 33 | + * @default 'https://${tenant}.onmicrosoft.com/${policy}/oauth2/v2.0/token' |
| 34 | + * @see https://learn.microsoft.com/en-us/azure/active-directory-b2c/openid-connect |
| 35 | + */ |
| 36 | + authorizationURL?: string |
| 37 | + /** |
| 38 | + * Azure OAuth Token URL |
| 39 | + * @default 'https://${tenant}.onmicrosoft.com/${policy}/oauth2/v2.0/token' |
| 40 | + * @see https://learn.microsoft.com/en-us/azure/active-directory-b2c/openid-connect |
| 41 | + */ |
| 42 | + tokenURL?: string |
| 43 | + /** |
| 44 | + * Azure OAuth User URL |
| 45 | + * @default 'https://graph.microsoft.com/v1.0/me' |
| 46 | + * @see https://docs.microsoft.com/en-us/graph/api/user-get?view=graph-rest-1.0&tabs=http |
| 47 | + */ |
| 48 | + userURL?: string |
| 49 | + /** |
| 50 | + * Extra authorization parameters to provide to the authorization URL |
| 51 | + * @see https://learn.microsoft.com/en-us/azure/active-directory-b2c/authorization-code-flow |
| 52 | + */ |
| 53 | + authorizationParams?: Record<string, string> |
| 54 | + /** |
| 55 | + * Redirect URL to prevent in prod prevent redirect_uri mismatch http to https |
| 56 | + * @default process.env.NUXT_OAUTH_AZUREB2C_REDIRECT_URL |
| 57 | + * @see https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow |
| 58 | + */ |
| 59 | + redirectURL?: string |
| 60 | +} |
| 61 | + |
| 62 | +export function defineOAuthAzureB2CEventHandler({ config, onSuccess, onError }: OAuthConfig<OAuthAzureB2CConfig>) { |
| 63 | + return eventHandler(async (event: H3Event) => { |
| 64 | + config = defu(config, useRuntimeConfig(event).oauth?.azureb2c, { |
| 65 | + authorizationParams: {}, |
| 66 | + }) as OAuthAzureB2CConfig |
| 67 | + |
| 68 | + const query = getQuery<{ code?: string, state?: string }>(event) |
| 69 | + |
| 70 | + if (!config.clientId || !config.policy || !config.tenant) { |
| 71 | + return handleMissingConfiguration(event, 'azureb2c', ['clientId', 'policy', 'tenant'], onError) |
| 72 | + } |
| 73 | + |
| 74 | + const authorizationURL = config.authorizationURL || `https://${config.tenant}.b2clogin.com/${config.tenant}.onmicrosoft.com/${config.policy}/oauth2/v2.0/authorize` |
| 75 | + const tokenURL = config.tokenURL || `https://${config.tenant}.b2clogin.com/${config.tenant}.onmicrosoft.com/${config.policy}/oauth2/v2.0/token` |
| 76 | + |
| 77 | + const redirectURL = config.redirectURL || getOAuthRedirectURL(event) |
| 78 | + |
| 79 | + // guarantee uniqueness of the scope |
| 80 | + config.scope = config.scope && config.scope.length > 0 ? config.scope : ['openid'] |
| 81 | + config.scope = [...new Set(config.scope)] |
| 82 | + |
| 83 | + // Create pkce verifier |
| 84 | + const verifier = await handlePkceVerifier(event) |
| 85 | + const state = await handleState(event) |
| 86 | + |
| 87 | + if (!query.code) { |
| 88 | + // Redirect to Azure B2C Oauth page |
| 89 | + return sendRedirect( |
| 90 | + event, |
| 91 | + withQuery(authorizationURL as string, { |
| 92 | + client_id: config.clientId, |
| 93 | + response_type: 'code', |
| 94 | + redirect_uri: redirectURL, |
| 95 | + scope: config.scope.join(' '), |
| 96 | + state, |
| 97 | + code_challenge: verifier.code_challenge, |
| 98 | + code_challenge_method: verifier.code_challenge_method, |
| 99 | + ...config.authorizationParams, |
| 100 | + }), |
| 101 | + ) |
| 102 | + } |
| 103 | + |
| 104 | + if (query.state !== state) { |
| 105 | + handleInvalidState(event, 'azureb2c', onError) |
| 106 | + } |
| 107 | + |
| 108 | + console.info('code verifier', verifier.code_verifier) |
| 109 | + const tokens = await requestAccessToken(tokenURL, { |
| 110 | + body: { |
| 111 | + grant_type: 'authorization_code', |
| 112 | + client_id: config.clientId, |
| 113 | + scope: config.scope.join(' '), |
| 114 | + code: query.code as string, |
| 115 | + redirect_uri: redirectURL, |
| 116 | + response_type: 'code', |
| 117 | + code_verifier: verifier.code_verifier, |
| 118 | + }, |
| 119 | + }) |
| 120 | + |
| 121 | + if (tokens.error) { |
| 122 | + return handleAccessTokenErrorResponse(event, 'azureb2c', tokens, onError) |
| 123 | + } |
| 124 | + |
| 125 | + const tokenType = tokens.token_type |
| 126 | + const accessToken = tokens.access_token |
| 127 | + const userURL = config.userURL || 'https://graph.microsoft.com/v1.0/me' |
| 128 | + // TODO: improve typing |
| 129 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 130 | + const user: any = await $fetch(userURL, { |
| 131 | + headers: { |
| 132 | + Authorization: `${tokenType} ${accessToken}`, |
| 133 | + }, |
| 134 | + }).catch((error) => { |
| 135 | + return { error } |
| 136 | + }) |
| 137 | + if (user.error) { |
| 138 | + const error = createError({ |
| 139 | + statusCode: 401, |
| 140 | + message: `azureb2c login failed: ${user.error || 'Unknown error'}`, |
| 141 | + data: user, |
| 142 | + }) |
| 143 | + if (!onError) throw error |
| 144 | + return onError(event, error) |
| 145 | + } |
| 146 | + |
| 147 | + return onSuccess(event, { |
| 148 | + tokens, |
| 149 | + user, |
| 150 | + }) |
| 151 | + }) |
| 152 | +} |
0 commit comments