38 lines
No EOL
1 KiB
TypeScript
38 lines
No EOL
1 KiB
TypeScript
export default defineEventHandler(async (event) => {
|
|
const config = useRuntimeConfig(event)
|
|
const body = await readBody(event)
|
|
|
|
if (!body?.code || !body?.redirectUri) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage: 'Missing code or redirectUri'
|
|
})
|
|
}
|
|
|
|
const tokenUrl = `${config.public.keycloakUrl}/realms/${config.public.keycloakRealm}/protocol/openid-connect/token`
|
|
|
|
const params = new URLSearchParams({
|
|
grant_type: 'authorization_code',
|
|
client_id: config.public.keycloakClientId,
|
|
client_secret: config.keycloakClientSecret,
|
|
code: body.code,
|
|
redirect_uri: body.redirectUri
|
|
})
|
|
|
|
try {
|
|
const response = await $fetch(tokenUrl, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/x-www-form-urlencoded'
|
|
},
|
|
body: params.toString()
|
|
})
|
|
|
|
return response
|
|
} catch (error: any) {
|
|
throw createError({
|
|
statusCode: error.response?.status || 500,
|
|
statusMessage: error.response?._data?.error_description || 'Failed to exchange authorization code'
|
|
})
|
|
}
|
|
}) |