-
Notifications
You must be signed in to change notification settings - Fork 303
/
webid-oidc.js
202 lines (167 loc) · 5.56 KB
/
webid-oidc.js
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
'use strict'
/**
* OIDC Relying Party API handler module.
*/
const express = require('express')
const { routeResolvedFile } = require('../../utils')
const bodyParser = require('body-parser').urlencoded({ extended: false })
const OidcManager = require('../../models/oidc-manager')
const { LoginRequest } = require('../../requests/login-request')
const { SharingRequest } = require('../../requests/sharing-request')
const restrictToTopDomain = require('../../handlers/restrict-to-top-domain')
const PasswordResetEmailRequest = require('../../requests/password-reset-email-request')
const PasswordChangeRequest = require('../../requests/password-change-request')
const { AuthCallbackRequest } = require('@solid/oidc-auth-manager').handlers
/**
* Sets up OIDC authentication for the given app.
*
* @param app {Object} Express.js app instance
* @param argv {Object} Config options hashmap
*/
function initialize (app, argv) {
const oidc = OidcManager.fromServerConfig(argv)
app.locals.oidc = oidc
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 => {
let 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
*/
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/', (req, res) => res.redirect('/logout'))
router.get('/goodbye', (req, res) => { res.render('auth/goodbye') })
// 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))
let oidcProviderApi = require('oidc-op-express')(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}
*/
function setAuthenticateHeader (req, res, err) {
let locals = req.app.locals
let errorParams = {
realm: locals.host.serverUri,
scope: 'openid webid',
error: err.error,
error_description: err.error_description,
error_uri: err.error_uri
}
let 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}
*/
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}
*/
function isEmptyToken (req) {
let header = req.get('Authorization')
if (!header) { return false }
if (header.startsWith('Bearer')) {
let fragments = header.split(' ')
if (fragments.length === 1) {
return true
} else if (!fragments[1]) {
return true
}
}
return false
}
module.exports = {
initialize,
isEmptyToken,
middleware,
setAuthenticateHeader,
statusCodeOverride
}