-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeycloak.ts
167 lines (151 loc) · 4.12 KB
/
keycloak.ts
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
import type { H3Event } from 'h3'
import {
eventHandler,
createError,
getQuery,
getRequestURL,
sendRedirect,
} from 'h3'
import { ofetch } from 'ofetch'
import { withQuery, parsePath } from 'ufo'
import { defu } from 'defu'
import { useRuntimeConfig } from '#imports'
import type { OAuthConfig } from '#auth-utils'
export interface OAuthKeycloakConfig {
/**
* Keycloak OAuth Client ID
* @default process.env.NUXT_OAUTH_KEYCLOAK_CLIENT_ID
*/
clientId?: string
/**
* Keycloak OAuth Client Secret
* @default process.env.NUXT_OAUTH_KEYCLOAK_CLIENT_SECRET
*/
clientSecret?: string
/**
* Keycloak OAuth Server URL
* @example http://192.168.1.10:8080/auth
* @default process.env.NUXT_OAUTH_KEYCLOAK_SERVER_URL
*/
serverUrl?: string
/**
* Keycloak OAuth Realm
* @default process.env.NUXT_OAUTH_KEYCLOAK_REALM
*/
realm?: string
/**
* Keycloak OAuth Scope
* @default []
* @see https://www.keycloak.org/docs/latest/authorization_services/
* @example ['openid']
*/
scope?: string[]
}
export function keycloakEventHandler({
config,
onSuccess,
onError,
}: OAuthConfig<OAuthKeycloakConfig>) {
return eventHandler(async (event: H3Event) => {
config = defu(
config,
// @ts-ignore
useRuntimeConfig(event).oauth?.keycloak
) as OAuthKeycloakConfig
const query = getQuery(event)
const { code } = query
if (query.error) {
const error = createError({
statusCode: 401,
message: `Keycloak login failed: ${query.error || 'Unknown error'}`,
data: query,
})
if (!onError) throw error
return onError(event, error)
}
if (
!config.clientId ||
!config.clientSecret ||
!config.serverUrl ||
!config.realm
) {
const error = createError({
statusCode: 500,
message:
'Missing NUXT_OAUTH_KEYCLOAK_CLIENT_ID or NUXT_OAUTH_KEYCLOAK_CLIENT_SECRET or NUXT_OAUTH_KEYCLOAK_SERVER_URL or NUXT_OAUTH_KEYCLOAK_REALM env variables.',
})
if (!onError) throw error
return onError(event, error)
}
const realmURL = `${config.serverUrl}/realms/${config.realm}`
const authorizationURL = `${realmURL}/protocol/openid-connect/auth`
const tokenURL = `${realmURL}/protocol/openid-connect/token`
const redirectUrl = getRequestURL(event).href
if (!code) {
config.scope = config.scope || ['openid']
// Redirect to Keycloak Oauth page
return sendRedirect(
event,
withQuery(authorizationURL, {
client_id: config.clientId,
redirect_uri: redirectUrl,
scope: config.scope.join(' '),
response_type: 'code',
})
)
}
config.scope = config.scope || []
if (!config.scope.includes('openid')) {
config.scope.push('openid')
}
const tokens: any = await ofetch(tokenURL, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
client_id: config.clientId,
client_secret: config.clientSecret,
grant_type: 'authorization_code',
redirect_uri: parsePath(redirectUrl).pathname,
code: code as string,
}).toString(),
}).catch((error) => {
return { error }
})
if (tokens.error) {
const error = createError({
statusCode: 401,
message: `Keycloak login failed: ${
tokens.error?.data?.error_description || 'Unknown error'
}`,
data: tokens,
})
if (!onError) throw error
return onError(event, error)
}
const accessToken = tokens.access_token
const user: any = await ofetch(
`${realmURL}/protocol/openid-connect/userinfo`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: 'application/json',
},
}
)
if (!user) {
const error = createError({
statusCode: 500,
message: 'Could not get Keycloak user',
data: tokens,
})
if (!onError) throw error
return onError(event, error)
}
return onSuccess(event, {
user,
tokens,
})
})
}