-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoidcApiProxy.js
More file actions
47 lines (40 loc) · 1.22 KB
/
oidcApiProxy.js
File metadata and controls
47 lines (40 loc) · 1.22 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
const express = require('express');
const axios = require('axios');
const cookieParser = require('cookie-parser');
function tryParseJson(obj) {
try {
return JSON.parse(obj);
} catch (err) {
return null;
}
}
module.exports = function createApiProxy(target, stateCookie = 'oidcState') {
const router = express.Router();
router.use(express.json());
router.use(cookieParser());
router.all('*', (req, res) => {
const oidcState = req.cookies[stateCookie];
if (!oidcState) {
return res.status(401).send({ error: 'Missing oidc cookie' });
}
const state = tryParseJson(oidcState);
if (!state || !state.jwt) {
return res.status(400).send({ error: 'Unable to parse OIDC state' });
}
return axios({
method: req.method,
url: `${target}/api/v1/user/${state.jwt.sub}${req.path}`,
validateStatus: () => true, // never error-out (always pass-thru)
headers: {
Authorization: `Bearer ${state.access_token}`,
},
params: req.query,
data: {},
}).then((resp) => {
res.status(resp.status).send(resp.data);
}).catch((err) => {
res.status(503).send({ error: `Error communicating with host: ${err}` });
});
});
return router;
};