-
Notifications
You must be signed in to change notification settings - Fork 11
/
server.js
241 lines (210 loc) · 6.4 KB
/
server.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
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
const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');
const os = require('os');
const yargs = require('yargs');
const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');
const helmet = require('helmet');
const passport = require('passport');
const JwtBearerStrategy = require('passport-oauth2-jwt-bearer').Strategy;
const request = require('request');
const OktaConfig = require('./js/config');
/**
* Arguments
*/
console.log();
console.log('loading configuration...');
var argv = yargs
.usage('\nSimple OAuth 2.0 protected resource server\n\n' +
'Usage:\n\t$0 -iss {url} -aud {uri}', {
port: {
description: 'Web server listener port',
required: true,
alias: 'p',
default: 8080
},
issuer: {
description: 'Access Token Issuer URL',
required: true,
alias: 'iss',
default: OktaConfig.orgUrl
},
audience: {
description: 'Acceess Token Audience URI',
required: true,
alias: 'aud',
default: OktaConfig.clientId
},
scope: {
description: 'OAuth 2.0 Scope for Protected Resource',
required: true,
alias: 'scp',
default: OktaConfig.resourceScope
},
apiToken: {
description: 'Okta Organization SSWS API Token for Social IdP Callbacks',
required: true,
alias: 'ssws',
default: OktaConfig.apiToken
}
})
.example('\t$0 --iss https://example.okta.com --aud ANRZhyDh8HBFN5abN6Rg', '')
.argv;
const issuerUrl = url.parse(argv.issuer);
const metadataUrl = argv.issuer + '/.well-known/openid-configuration';
const orgUrl = issuerUrl.protocol + '//' + issuerUrl.host + (issuerUrl.port ? ':' + issuerUrl.port : '');
console.log();
console.log('Listener Port:\n\t' + argv.port);
console.log('Issuer URL:\n\t' + argv.issuer);
console.log('Audience URI:\n\t' + argv.audience);
console.log('Metadata URL:\n\t' + metadataUrl);
console.log('Organization URL:\n\t' + orgUrl);
console.log();
/**
* Globals
*/
const app = express();
const httpServer = http.createServer(app);
const imgString = new Buffer(
fs.readFileSync(path.join(__dirname, './images/oauth2.png'))
).toString('base64');
const sessionHandler = require('express-session')({
secret: 'if you don\t know, now you know',
resave: true,
saveUninitialized: true
});
/**
* Middleware
*/
app.set('port', argv.port);
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use('/', express.static(__dirname));
app.use(bodyParser.json());
app.use(helmet())
app.use(passport.initialize());
/**
* Routes
*/
app.get('/social/callback', sessionHandler, function(req, res, next) {
const txId = req.query.tx_id;
console.log('Fetching IdP transaction %s', txId);
if (txId) {
request({
method: 'GET',
json: true,
uri: orgUrl + '/api/v1/idps/tx/' + txId + '/target',
headers: {
'authorization': 'SSWS ' + argv.apiToken
}
}, function(txErr, txRes, txBody) {
if (txErr || txRes.statusCode < 200 || txRes.statusCode >= 300) {
console.log('Unable to fetch IdP transaction %s due to HTTP Error: %s ', txId, txErr || txRes.statusCode);
} else {
console.log('IdP transaction: %j', txBody)
req.session.tx = {
id: txId,
profile: txBody.profile
}
return res.render('register', {
profile: txBody.profile,
});
}
});
}
});
app.post('/social/callback', [bodyParser.urlencoded({extended: false}), sessionHandler], function(req, res, next) {
if (req.session.tx) {
const txId = req.session.tx.id;
const profile = {
customerId: req.body.customerId,
streetAddress: req.body.streetAddress,
city: req.body.city,
zipCode: req.body.postalCode
};
console.log('Registering additional profile %j for IdP transaction %s', profile, txId);
request({
method: 'POST',
json: true,
uri: orgUrl + '/api/v1/idps/tx/' + txId + '/lifecycle/provision',
headers: {
'authorization': 'SSWS ' + argv.apiToken
},
body: {
profile: profile
}
}, function(txErr, txRes, txBody) {
if (txErr || txRes.statusCode < 200 || txRes.statusCode >= 300) {
console.log('Unable to fetch IdP transaction %s due to HTTP Error: %s ', txId, txErr || txRes.statusCode);
} else {
console.log('registration response %j', txBody);
if (txBody.status === 'SUCCESS') {
req.session.destroy();
return res.render('finish', {
url: orgUrl + '/api/v1/idps/tx/' + txId + '/finish',
sessionToken: txBody.sessionToken
});
} else {
return res.json(txBody);
}
}
});
}
});
app.get('/claims',
passport.authenticate('oauth2-jwt-bearer', { session: false }),
function(req, res) {
res.json(req.user);
});
app.get('/protected',
passport.authenticate('oauth2-jwt-bearer', { scopes: argv.scope, session: false }),
function(req, res) {
console.log('Accessing protected resource as ' + req.user.sub);
res.set('Content-Type', 'application/x-octet-stream');
res.send(imgString);
});
/**
* Fetch metadata to obtain JWKS signing keys
*/
console.log('fetching issuer metadata configuration from %s...', metadataUrl);
request({
json: true,
uri: metadataUrl,
strictSSL: true
}, function(err, res, body) {
if (err || res.statusCode < 200 || res.statusCode >= 300) {
console.log('Unable to fetch issuer metadata configuration due to HTTP Error: %s ', res.statusCode);
return process.exit(1);
}
/**
* Configure JwtBearerStrategy with JWKS
*/
console.log('trusting tokens signed with keys from %s...', res.body.jwks_uri);
passport.use(new JwtBearerStrategy({
issuer: argv.issuer,
audience: argv.audience,
realm: 'OKTA',
jwksUrl: res.body.jwks_uri
}, function(token, done) {
// done(err, user, info)
return done(null, token);
}));
/**
* Start Server
*/
console.log();
console.log('starting server...');
httpServer.listen(app.get('port'), function() {
var scheme = argv.https ? 'https' : 'http',
address = httpServer.address(),
hostname = os.hostname();
baseUrl = address.address === '0.0.0.0' ?
scheme + '://' + hostname + ':' + address.port :
scheme + '://localhost:' + address.port;
console.log('listening on port: ' + app.get('port'));
console.log();
});
});