forked from Unleash/unleash-docker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeycloak-auth-hook.js
102 lines (89 loc) · 3.04 KB
/
keycloak-auth-hook.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
'use strict';
/**
* Keycloak hook for securing an Unleash server
*
* This example assumes that all users authenticating via
* keycloak should have access. You would probably limit access
* to users you trust.
*
* The implementation assumes the following environment variables:
*
* - AUTH_HOST
* - AUTH_REALM
* - AUTH_CLIENT_ID
*/
const { User, AuthenticationRequired } = require('unleash-server');
const KeycloakStrategy = require('@exlinc/keycloak-passport');
const passport = require('passport');
const host = process.env.AUTH_HOST;
const realm = process.env.AUTH_REALM;
const clientID = process.env.AUTH_CLIENT_ID;
const contextPath = process.env.CONTEXT_PATH === '/' ? '' : process.env.CONTEXT_PATH;
const clientSecret = process.env.CLIENT_SECRET;
const secret = process.env.SECRET;
passport.use(
'keycloak',
new KeycloakStrategy(
{
host,
realm,
clientID,
clientSecret: clientSecret,
callbackURL: `${contextPath}/api/auth/callback`,
authorizationURL: `${host}/auth/realms/${realm}/protocol/openid-connect/auth`,
tokenURL: `${host}/auth/realms/${realm}/protocol/openid-connect/token`,
userInfoURL: `${host}/auth/realms/${realm}/protocol/openid-connect/userinfo`,
},
(accessToken, refreshToken, profile, done) => {
done(
null,
new User({
name: profile.fullName,
email: profile.email,
})
);
}
)
);
function enableKeycloakOauth(app) {
console.log(`Initializing keycloak auth. Host: ${host}. Realm: ${realm}. ClientID: ${clientID}. Context path: ${contextPath}`);
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser((user, done) => done(null, user));
passport.deserializeUser((user, done) => done(null, user));
app.use('/api/client', (req, res, next) => {
if (req.header('Authorization') !== secret) {
res.sendStatus(401);
} else {
next();
}
});
app.get('/api/admin/login', passport.authenticate('keycloak'));
app.get(
'/api/auth/callback',
passport.authenticate('keycloak'),
(req, res) => {
console.log('Authenticated', res);
res.redirect(`${contextPath}/`);
}
);
app.use('/api/admin/', (req, res, next) => {
if (req.user) {
next();
} else {
// Instruct unleash-frontend to pop-up auth dialog
return res
.status('401')
.json(
new AuthenticationRequired({
path: `${contextPath}/api/admin/login`,
type: 'custom',
message: `You have to identify yourself in order to use Unleash.
Click the button and follow the instructions.`,
})
)
.end();
}
});
}
module.exports = enableKeycloakOauth;