forked from oauthinaction/oauth-in-action-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
206 lines (170 loc) · 6.15 KB
/
client.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
var express = require("express");
var request = require("sync-request");
var url = require("url");
var qs = require("qs");
var querystring = require('querystring');
var cons = require('consolidate');
var randomstring = require("randomstring");
var __ = require('underscore');
__.string = require('underscore.string');
var app = express();
app.engine('html', cons.underscore);
app.set('view engine', 'html');
app.set('views', 'files/client');
// authorization server information
var authServer = {
authorizationEndpoint: 'http://localhost:9001/authorize',
tokenEndpoint: 'http://localhost:9001/token'
};
// client information
var client = {
"client_id": "oauth-client-1",
"client_secret": "oauth-client-secret-1",
"redirect_uris": ["http://localhost:9000/callback"],
"scope": "foo"
};
var protectedResource = 'http://localhost:9002/resource';
var state = null;
var access_token = '987tghjkiu6trfghjuytrghj';
var scope = null;
var refresh_token = 'j2r3oj32r23rmasd98uhjrk2o3i';
app.get('/', function (req, res) {
res.render('index', {access_token: access_token, scope: scope, refresh_token: refresh_token});
});
app.get('/authorize', function(req, res){
access_token = null;
scope = null;
state = randomstring.generate();
var authorizeUrl = buildUrl(authServer.authorizationEndpoint, {
response_type: 'code',
scope: client.scope,
client_id: client.client_id,
redirect_uri: client.redirect_uris[0],
state: state
});
console.log("redirect", authorizeUrl);
res.redirect(authorizeUrl);
});
app.get('/callback', function(req, res){
if (req.query.error) {
// it's an error response, act accordingly
res.render('error', {error: req.query.error});
return;
}
var resState = req.query.state;
if (resState != state) {
console.log('State DOES NOT MATCH: expected %s got %s', state, resState);
res.render('error', {error: 'State value did not match'});
return;
}
var code = req.query.code;
var form_data = qs.stringify({
grant_type: 'authorization_code',
code: code,
redirect_uri: client.redirect_uris[0]
});
var headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + encodeClientCredentials(client.client_id, client.client_secret)
};
var tokRes = request('POST', authServer.tokenEndpoint,
{
body: form_data,
headers: headers
}
);
console.log('Requesting access token for code %s',code);
if (tokRes.statusCode >= 200 && tokRes.statusCode < 300) {
var body = JSON.parse(tokRes.getBody());
access_token = body.access_token;
console.log('Got access token: %s', access_token);
if (body.refresh_token) {
refresh_token = body.refresh_token;
console.log('Got refresh token: %s', refresh_token);
}
scope = body.scope;
console.log('Got scope: %s', scope);
res.render('index', {access_token: access_token, scope: scope, refresh_token: refresh_token});
} else {
res.render('error', {error: 'Unable to fetch access token, server response: ' + tokRes.statusCode})
}
});
app.get('/fetch_resource', function(req, res) {
console.log('Making request with access token %s', access_token);
var headers = {
'Authorization': 'Bearer ' + access_token,
'Content-Type': 'application/x-www-form-urlencoded'
};
var resource = request('POST', protectedResource,
{headers: headers}
);
if (resource.statusCode >= 200 && resource.statusCode < 300) {
var body = JSON.parse(resource.getBody());
res.render('data', {resource: body});
return;
} else {
/*
* Instead of always returning an error like we do here, refresh the access token if we have a refresh token
*/
console.log("resource status error code " + resource.statusCode);
res.render('error', {error: 'Unable to fetch resource. Status ' + resource.statusCode});
}
});
var refreshAccessToken = function(req, res) {
var form_data = qs.stringify({
grant_type: 'refresh_token',
refresh_token: refresh_token
});
var headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + encodeClientCredentials(client.client_id, client.client_secret)
};
console.log('Refreshing token %s', refresh_token);
var tokRes = request('POST', authServer.tokenEndpoint, {
body: form_data,
headers: headers
});
if (tokRes.statusCode >= 200 && tokRes.statusCode < 300) {
var body = JSON.parse(tokRes.getBody());
access_token = body.access_token;
console.log('Got access token: %s', access_token);
if (body.refresh_token) {
refresh_token = body.refresh_token;
console.log('Got refresh token: %s', refresh_token);
}
scope = body.scope;
console.log('Got scope: %s', scope);
// try again
res.redirect('/fetch_resource');
return;
} else {
console.log('No refresh token, asking the user to get a new access token');
// tell the user to get a new access token
refresh_token = null;
res.render('error', {error: 'Unable to refresh token.'});
return;
}
};
var buildUrl = function(base, options, hash) {
var newUrl = url.parse(base, true);
delete newUrl.search;
if (!newUrl.query) {
newUrl.query = {};
}
__.each(options, function(value, key, list) {
newUrl.query[key] = value;
});
if (hash) {
newUrl.hash = hash;
}
return url.format(newUrl);
};
var encodeClientCredentials = function(clientId, clientSecret) {
return Buffer.from(querystring.escape(clientId) + ':' + querystring.escape(clientSecret)).toString('base64');
};
app.use('/', express.static('files/client'));
var server = app.listen(9000, 'localhost', function () {
var host = server.address().address;
var port = server.address().port;
console.log('OAuth Client is listening at http://%s:%s', host, port);
});