-
Notifications
You must be signed in to change notification settings - Fork 306
Expand file tree
/
Copy pathwebid-oidc.mjs
More file actions
299 lines (249 loc) · 8.02 KB
/
Copy pathwebid-oidc.mjs
File metadata and controls
299 lines (249 loc) · 8.02 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
/**
* OIDC Relying Party API handler module.
*/
import express from 'express'
import { routeResolvedFile } from '../../utils.mjs'
import bodyParserPkg from 'body-parser'
import { fromServerConfig } from '../../models/oidc-manager.mjs'
import { LoginRequest } from '../../requests/login-request.mjs'
import { SharingRequest } from '../../requests/sharing-request.mjs'
import debug from '../../debug.mjs'
import restrictToTopDomain from '../../handlers/restrict-to-top-domain.mjs'
import PasswordResetEmailRequest from '../../requests/password-reset-email-request.mjs'
import PasswordChangeRequest from '../../requests/password-change-request.mjs'
import oidcOpExpress from 'oidc-op-express'
import oidcAuthManager from '@solid/oidc-auth-manager'
const { urlencoded } = bodyParserPkg
const bodyParser = urlencoded({ extended: false })
const { AuthCallbackRequest } = oidcAuthManager.handlers
function oidcCookieNames (req) {
const provider = req.app?.locals?.oidc?.provider
if (!provider || typeof provider.configuration !== 'function') {
return []
}
const cookieNames = provider.configuration('cookies')?.names || {}
const baseNames = Object.values(cookieNames).filter(Boolean)
const expandedNames = baseNames.flatMap(name => [
name,
`${name}.sig`,
`${name}.legacy`,
`${name}.legacy.sig`
])
return Array.from(new Set(expandedNames))
}
function cookieNamesFromRequest (req) {
const cookieHeader = req.headers?.cookie
if (!cookieHeader) {
return []
}
return cookieHeader
.split(';')
.map(fragment => fragment.trim())
.filter(Boolean)
.map(fragment => fragment.split('=')[0].trim())
.filter(Boolean)
}
function clearAuthCookies (res, domain, cookieNames) {
const cookiePaths = ['/', '/.oidc']
const allCookieNames = Array.from(new Set([
'nssidp.sid',
'nssidp.sid.sig',
'nssidp.sid.legacy',
'nssidp.sid.legacy.sig',
...(cookieNames || [])
]))
for (const path of cookiePaths) {
const noDomainOptions = { path }
for (const name of allCookieNames) {
res.clearCookie(name, noDomainOptions)
}
if (domain) {
const domainOptions = { domain, path }
for (const name of allCookieNames) {
res.clearCookie(name, domainOptions)
}
}
}
}
function renderGoodbyeAndClearSession (req, res, next) {
const domain = req.session?.cookie?.domain
const providerCookieNames = oidcCookieNames(req)
const incomingCookieNames = cookieNamesFromRequest(req)
const cookiesToClear = Array.from(new Set([...providerCookieNames, ...incomingCookieNames]))
if (!req.session) {
clearAuthCookies(res, domain, cookiesToClear)
return res.render('auth/goodbye')
}
req.session.destroy((err) => {
if (err) {
return next(err)
}
clearAuthCookies(res, domain, cookiesToClear)
res.render('auth/goodbye')
})
}
/**
* Sets up OIDC authentication for the given app.
*
* @param app {Object} Express.js app instance
* @param argv {Object} Config options hashmap
*/
export function initialize (app, argv) {
const oidc = fromServerConfig(argv)
app.locals.oidc = oidc
// Store initialization function to be called after server starts listening
// (OIDC client registration needs the server to be up to fetch openid-configuration)
app.locals.initFunction = () => oidc.initialize()
// Attach the OIDC API
app.use('/', middleware(oidc))
// Perform the actual authentication
app.use('/', async (req, res, next) => {
oidc.rs.authenticate({ tokenTypesSupported: argv.tokenTypesSupported })(req, res, (err) => {
// Error handling should be deferred to the ldp in case a user with a bad token is trying
// to access a public resource
if (err) {
req.authError = err
res.status(200)
}
next()
})
})
// Expose session.userId
app.use('/', (req, res, next) => {
oidc.webIdFromClaims(req.claims)
.then(webId => {
if (webId) {
req.session.userId = webId
}
next()
})
.catch(err => {
const error = new Error('Could not verify Web ID from token claims')
error.statusCode = 401
error.statusText = 'Invalid login'
error.cause = err
console.error(err)
next(error)
})
})
}
/**
* Returns a router with OIDC Relying Party and Identity Provider middleware:
*
* @method middleware
*
* @param oidc {OidcManager}
*
* @return {Router} Express router
*/
export function middleware (oidc) {
const router = express.Router('/')
// User-facing Authentication API
router.get(['/login', '/signin'], LoginRequest.get)
router.post('/login/password', bodyParser, LoginRequest.loginPassword)
router.post('/login/tls', bodyParser, LoginRequest.loginTls)
router.get('/sharing', SharingRequest.get)
router.post('/sharing', bodyParser, SharingRequest.share)
router.get('/account/password/reset', restrictToTopDomain, PasswordResetEmailRequest.get)
router.post('/account/password/reset', restrictToTopDomain, bodyParser, PasswordResetEmailRequest.post)
router.get('/account/password/change', restrictToTopDomain, PasswordChangeRequest.get)
router.post('/account/password/change', restrictToTopDomain, bodyParser, PasswordChangeRequest.post)
router.get([
'/.well-known/solid/logout',
'/.well-known/solid/logout/',
'/solid/logout',
'/solid/logout/'
], (req, res) => {
res.redirect('/goodbye')
})
router.get(['/logout', '/logout/'], (req, res) => {
res.redirect('/goodbye')
})
router.get('/goodbye', renderGoodbyeAndClearSession)
// The relying party callback is called at the end of the OIDC signin process
router.get('/api/oidc/rp/:issuer_id', AuthCallbackRequest.get)
// Static assets related to authentication
const authAssets = [
['/.well-known/solid/login/', '../static/popup-redirect.html', false],
['/common/', 'solid-auth-client/dist-popup/popup.html']
]
authAssets.map(args => routeResolvedFile(router, ...args))
// Initialize the OIDC Identity Provider routes/api
// router.get('/.well-known/openid-configuration', discover.bind(provider))
// router.get('/jwks', jwks.bind(provider))
// router.post('/register', register.bind(provider))
// router.get('/authorize', authorize.bind(provider))
// router.post('/authorize', authorize.bind(provider))
// router.post('/token', token.bind(provider))
// router.get('/userinfo', userinfo.bind(provider))
// router.get('/logout', logout.bind(provider))
const oidcProviderApi = oidcOpExpress(oidc.provider)
router.use('/', oidcProviderApi)
return router
}
/**
* Sets the `WWW-Authenticate` response header for 401 error responses.
* Used by error-pages handler.
*
* @param req {IncomingRequest}
* @param res {ServerResponse}
* @param err {Error}
*/
export function setAuthenticateHeader (req, res, err) {
const locals = req.app.locals
const errorParams = {
realm: locals.host.serverUri,
scope: 'openid webid',
error: err.error,
error_description: err.error_description,
error_uri: err.error_uri
}
const challengeParams = Object.keys(errorParams)
.filter(key => !!errorParams[key])
.map(key => `${key}="${errorParams[key]}"`)
.join(', ')
res.set('WWW-Authenticate', 'Bearer ' + challengeParams)
}
/**
* Provides custom logic for error status code overrides.
*
* @param statusCode {number}
* @param req {IncomingRequest}
*
* @returns {number}
*/
export function statusCodeOverride (statusCode, req) {
if (isEmptyToken(req)) {
return 400
} else {
return statusCode
}
}
/**
* Tests whether the `Authorization:` header includes an empty or missing Bearer
* token.
*
* @param req {IncomingRequest}
*
* @returns {boolean}
*/
export function isEmptyToken (req) {
const header = req.get('Authorization')
if (!header) { return false }
if (header.startsWith('Bearer')) {
const fragments = header.split(' ')
if (fragments.length === 1) {
return true
} else if (!fragments[1]) {
return true
}
}
return false
}
export default {
initialize,
isEmptyToken,
middleware,
setAuthenticateHeader,
statusCodeOverride
}