forked from mulesoft-labs/js-client-oauth2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client-oauth2.js
795 lines (692 loc) · 20.4 KB
/
client-oauth2.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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
/* global define */
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['popsicle'], factory)
} else if (typeof exports === 'object') {
module.exports = factory(require('popsicle'))
} else {
root.ClientOAuth2 = factory(root.popsicle)
}
})(this, function (popsicle) {
var _hasOwnProperty = Object.prototype.hasOwnProperty
var btoa = typeof Buffer === 'function' ? btoaBuffer : window.btoa
/**
* Format error response types to regular strings for displaying to clients.
*
* Reference: http://tools.ietf.org/html/rfc6749#section-4.1.2.1
*
* @type {Object}
*/
var ERROR_RESPONSES = {
'invalid_request': [
'The request is missing a required parameter, includes an',
'invalid parameter value, includes a parameter more than',
'once, or is otherwise malformed.'
].join(' '),
'invalid_client': [
'Client authentication failed (e.g., unknown client, no',
'client authentication included, or unsupported',
'authentication method).'
].join(' '),
'invalid_grant': [
'The provided authorization grant (e.g., authorization',
'code, resource owner credentials) or refresh token is',
'invalid, expired, revoked, does not match the redirection',
'URI used in the authorization request, or was issued to',
'another client.'
].join(' '),
'unauthorized_client': [
'The client is not authorized to request an authorization',
'code using this method.'
].join(' '),
'unsupported_grant_type': [
'The authorization grant type is not supported by the',
'authorization server.'
].join(' '),
'access_denied': [
'The resource owner or authorization server denied the request.'
].join(' '),
'unsupported_response_type': [
'The authorization server does not support obtaining',
'an authorization code using this method.'
].join(' '),
'invalid_scope': [
'The requested scope is invalid, unknown, or malformed.'
].join(' '),
'server_error': [
'The authorization server encountered an unexpected',
'condition that prevented it from fulfilling the request.',
'(This error code is needed because a 500 Internal Server',
'Error HTTP status code cannot be returned to the client',
'via an HTTP redirect.)'
].join(' '),
'temporarily_unavailable': [
'The authorization server is currently unable to handle',
'the request due to a temporary overloading or maintenance',
'of the server.'
].join(' ')
}
/**
* Iterate over a source object and copy properties to the destination object.
*
* @param {Object} dest
* @param {Object} source
* @return {Object}
*/
function assign (dest /*, ...source */) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i]
for (var key in source) {
if (_hasOwnProperty.call(source, key)) {
dest[key] = source[key]
}
}
}
return dest
}
/**
* Support base64 in node like how it works in the browser.
*
* @param {String} string
* @return {String}
*/
function btoaBuffer (string) {
return new Buffer(string).toString('base64')
}
/**
* Check if properties exist on an object and throw when they aren't.
*
* @throws {TypeError} If an expected property is missing.
*
* @param {Object} obj
* @param {Array} props
*/
function expects (obj, props) {
for (var i = 0; i < props.length; i++) {
var prop = props[i]
if (obj[prop] == null) {
throw new TypeError('Expected "' + prop + '" to exist')
}
}
}
/**
* Create a new object based on a source object with keys omitted.
*
* @param {Object} source
* @param {Array} keys
* @return {Object}
*/
function omit (source, keys) {
var obj = {}
// Iterate over the source object and set properties on a new object.
Object.keys(source || {}).forEach(function (key) {
if (keys.indexOf(key) === -1) {
obj[key] = source[key]
}
})
return obj
}
/**
* Convert a query string into an object.
*
* @param {String} qs
* @param {String} sep
* @param {String} eq
* @return {Object}
*/
function decodeQuery (qs, sep, eq) {
eq = eq || '='
sep = sep || '&'
qs = qs.split(sep)
var obj = {}
var maxKeys = 1000
var len = Math.min(qs.length, maxKeys)
for (var i = 0; i < len; i++) {
var key = qs[i].replace(/\+/g, '%20')
var value = ''
var index = key.indexOf(eq)
if (index !== -1) {
value = key.substr(index + 1)
key = key.substr(0, index)
}
key = decodeURIComponent(key)
value = decodeURIComponent(value)
if (!_hasOwnProperty.call(obj, key)) {
obj[key] = value
} else if (Array.isArray(obj[key])) {
obj[key].push(value)
} else {
obj[key] = [obj[key], value]
}
}
return obj
}
/**
* Pull an authentication error from the response data.
*
* @param {Object} data
* @return {String}
*/
function getAuthError (data) {
var message = ERROR_RESPONSES[data.error] ||
data.error ||
data.error_message
// Return an error instance with the message if it exists.
return message && new Error(message)
}
/**
* Handle the authentication response object.
*
* @param {Object} res
* @return {Promise}
*/
function handleAuthResponse (res) {
var data = res.body
var err = getAuthError(data)
// If the response contains an error, reject the refresh token.
if (err) {
return Promise.reject(err)
}
return data
}
/**
* Sanitize the scopes option to be a string.
*
* @param {Array} scopes
* @return {String}
*/
function sanitizeScope (scopes) {
if (!Array.isArray(scopes)) {
return scopes == null ? '' : String(scopes)
}
return scopes.join(' ')
}
/**
* Create a request uri based on an options object and token type.
*
* @param {Object} options
* @param {String} tokenType
* @return {String}
*/
function createUri (options, tokenType) {
// Check the required parameters are set.
expects(options, [
'clientId',
'redirectUri',
'authorizationUri'
])
var clientId = encodeURIComponent(options.clientId)
var redirectUri = encodeURIComponent(options.redirectUri)
var scopes = encodeURIComponent(sanitizeScope(options.scopes))
var uri = options.authorizationUri + '?client_id=' + clientId +
'&redirect_uri=' + redirectUri +
'&scope=' + scopes +
'&response_type=' + tokenType
if (options.state) {
uri += '&state=' + encodeURIComponent(options.state)
}
return uri
}
/**
* Create basic auth header.
*
* @param {String} username
* @param {String} password
* @return {String}
*/
function auth (username, password) {
return 'Basic ' + btoa(string(username) + ':' + string(password))
}
/**
* Ensure a value is a string.
*
* @param {String} str
* @return {String}
*/
function string (str) {
return str == null ? '' : String(str)
}
/**
* Construct an object that can handle the multiple OAuth 2.0 flows.
*
* @param {Object} options
*/
function ClientOAuth2 (options) {
this.options = options
this.code = new CodeFlow(this)
this.token = new TokenFlow(this)
this.owner = new OwnerFlow(this)
this.credentials = new CredentialsFlow(this)
this.jwt = new JwtBearerFlow(this)
}
/**
* Alias the token constructor.
*
* @type {Function}
*/
ClientOAuth2.Token = ClientOAuth2Token
/**
* Create a new token from existing data.
*
* @param {String} access
* @param {String} [refresh]
* @param {String} [type]
* @param {Object} [data]
* @return {Object}
*/
ClientOAuth2.prototype.createToken = function (access, refresh, type, data) {
data = assign({}, data, {
access_token: access,
refresh_token: refresh,
token_type: type
})
return new ClientOAuth2Token(this, data)
}
/**
* Using the built-in request method, we'll automatically attempt to parse
* the response.
*
* @param {Object} options
* @return {Promise}
*/
ClientOAuth2.prototype._request = function (options) {
return this.request(options)
.then(function (res) {
if (res.status < 200 || res.status >= 399) {
var err = new Error('HTTP status ' + res.status)
err.status = res.status
err.body = res.body
return Promise.reject(err)
}
return res
})
}
/**
* Set `popsicle` as the default request method.
*/
ClientOAuth2.prototype.request = popsicle
/**
* General purpose client token generator.
*
* @param {Object} client
* @param {Object} data
*/
function ClientOAuth2Token (client, data) {
this.client = client
this.data = omit(data, [
'access_token', 'refresh_token', 'token_type', 'expires_in', 'scope',
'state', 'error', 'error_description', 'error_uri'
])
this.tokenType = (data.token_type || 'bearer').toLowerCase()
this.accessToken = data.access_token
this.refreshToken = data.refresh_token
this.expiresIn(data.expires_in)
}
/**
* Expire after some seconds.
*
* @param {Number} duration
* @return {Date}
*/
ClientOAuth2Token.prototype.expiresIn = function (duration) {
if (!isNaN(duration)) {
this.expires = new Date()
this.expires.setSeconds(this.expires.getSeconds() + duration)
} else {
this.expires = undefined
}
return this.expires
}
/**
* Sign a standardised request object with user authentication information.
*
* @param {Object} opts
* @return {Object}
*/
ClientOAuth2Token.prototype.sign = function (opts) {
if (!this.accessToken) {
throw new Error('Unable to sign without access token')
}
opts.headers = opts.headers || {}
if (this.tokenType === 'bearer') {
opts.headers.Authorization = 'Bearer ' + this.accessToken
} else {
var parts = opts.url.split('#')
var token = 'access_token=' + this.accessToken
var url = parts[0].replace(/[?&]access_token=[^&#]/, '')
var fragment = parts[1] ? '#' + parts[1] : ''
// Prepend the correct query string parameter to the url.
opts.url = url + (url.indexOf('?') > -1 ? '&' : '?') + token + fragment
// Attempt to avoid storing the url in proxies, since the access token
// is exposed in the query parameters.
opts.headers.Pragma = 'no-store'
opts.headers['Cache-Control'] = 'no-store'
}
return opts
}
/**
* Make a HTTP request as the user.
*
* @param {Object} opts
* @return {Promise}
*/
ClientOAuth2Token.prototype.request = function (opts) {
return this.client.request(this.sign(opts))
}
/**
* Refresh a user access token with the supplied token.
*
* @return {Promise}
*/
ClientOAuth2Token.prototype.refresh = function () {
var self = this
var options = this.client.options
if (!this.refreshToken) {
return Promise.reject(new Error('No refresh token set'))
}
return this.client._request({
url: options.accessTokenUri,
method: 'POST',
headers: {
'Accept': 'application/json, application/x-www-form-urlencoded',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': auth(options.clientId, options.clientSecret)
},
body: {
refresh_token: this.refreshToken,
grant_type: 'refresh_token'
}
})
.then(handleAuthResponse)
.then(function (data) {
self.accessToken = data.access_token
self.refreshToken = data.refresh_token
self.expiresIn(data.expires_in)
return self
})
}
/**
* Check whether the token has expired.
*
* @return {Boolean}
*/
ClientOAuth2Token.prototype.expired = function () {
if (this.expires) {
return Date.now() > this.expires.getTime()
}
return false
}
/**
* Support resource owner password credentials OAuth 2.0 grant.
*
* Reference: http://tools.ietf.org/html/rfc6749#section-4.3
*
* @param {ClientOAuth2} client
*/
function OwnerFlow (client) {
this.client = client
}
/**
* Make a request on behalf of the user credentials to get an acces token.
*
* @param {String} username
* @param {String} password
* @return {Promise}
*/
OwnerFlow.prototype.getToken = function (username, password) {
var self = this
var options = this.client.options
return this.client._request({
url: options.accessTokenUri,
method: 'POST',
headers: {
'Accept': 'application/json, application/x-www-form-urlencoded',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': auth(options.clientId, options.clientSecret)
},
body: {
scope: sanitizeScope(options.scopes),
username: username,
password: password,
grant_type: 'password'
}
})
.then(handleAuthResponse)
.then(function (data) {
return new ClientOAuth2Token(self.client, data)
})
}
/**
* Support implicit OAuth 2.0 grant.
*
* Reference: http://tools.ietf.org/html/rfc6749#section-4.2
*
* @param {ClientOAuth2} client
*/
function TokenFlow (client) {
this.client = client
}
/**
* Get the uri to redirect the user to for implicit authentication.
*
* @param {Object} options
* @return {String}
*/
TokenFlow.prototype.getUri = function (options) {
options = assign({}, this.client.options, options)
return createUri(options, 'token')
}
/**
* Get the user access token from the uri.
*
* @param {String} uri
* @param {String} [state]
* @return {Promise}
*/
TokenFlow.prototype.getToken = function (uri, state) {
var data = {}
var options = this.client.options
// Make sure the uri matches our expected redirect uri.
if (uri.substr(0, options.redirectUri.length) !== options.redirectUri) {
return Promise.reject(new Error('Should match redirect uri: ' + uri))
}
var queryIndex = uri.indexOf('?')
var fragmentIndex = uri.indexOf('#')
// If no query string or fragment exists, we won't be able to parse
// any useful information from the uri.
if (queryIndex === -1 && fragmentIndex === -1) {
return Promise.reject(new Error('Unable to process uri: ' + uri))
}
// Extract the query string and parse. This is needed because Instagram
// has a bug where the OAuth 2.0 state is passed back via the query string.
if (queryIndex > -1 && queryIndex < fragmentIndex) {
var endIndex = fragmentIndex === -1 ? uri.length : fragmentIndex
var query = uri.slice(queryIndex + 1, endIndex)
assign(data, decodeQuery(query))
}
// Extract data from the uri fragment, which is more important than the
// query string which shouldn't hold any information.
if (fragmentIndex > -1) {
var fragment = uri.substr(fragmentIndex + 1)
assign(data, decodeQuery(fragment))
}
var err = getAuthError(data)
// Check if the query string was populated with a known error.
if (err) {
return Promise.reject(err)
}
// Check whether the state matches.
if (state != null && data.state !== state) {
return Promise.reject(new Error('Invalid state: ' + data.state))
}
// Initalize a new token and return.
return Promise.resolve(new ClientOAuth2Token(this.client, data))
}
/**
* Support client credentials OAuth 2.0 grant.
*
* Reference: http://tools.ietf.org/html/rfc6749#section-4.4
*
* @param {ClientOAuth2} client
*/
function CredentialsFlow (client) {
this.client = client
}
/**
* Request an access token using the client credentials.
*
* @param {Object} [options]
* @return {Promise}
*/
CredentialsFlow.prototype.getToken = function (options) {
var self = this
options = assign({}, this.client.options, options)
expects(options, [
'clientId',
'clientSecret',
'accessTokenUri'
])
return this.client._request({
url: options.accessTokenUri,
method: 'POST',
headers: {
'Accept': 'application/json, application/x-www-form-urlencoded',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': auth(options.clientId, options.clientSecret)
},
body: {
scope: sanitizeScope(options.scopes),
grant_type: 'client_credentials'
}
})
.then(handleAuthResponse)
.then(function (data) {
return new ClientOAuth2Token(self.client, data)
})
}
/**
* Support authorization code OAuth 2.0 grant.
*
* Reference: http://tools.ietf.org/html/rfc6749#section-4.1
*
* @param {ClientOAuth2} client
*/
function CodeFlow (client) {
this.client = client
}
/**
* Generate the uri for doing the first redirect.
*
* @return {String}
*/
CodeFlow.prototype.getUri = function (options) {
options = assign({}, this.client.options, options)
return createUri(options, 'code')
}
/**
* Get the code token from the redirected uri and make another request for
* the user access token.
*
* @param {String} uri
* @param {String} [state]
* @return {Promise}
*/
CodeFlow.prototype.getToken = function (uri, state) {
var self = this
var options = this.client.options
expects(options, [
'clientId',
'clientSecret',
'redirectUri',
'accessTokenUri'
])
// Make sure the uri matches our expected redirect uri.
if (uri.substr(0, options.redirectUri.length) !== options.redirectUri) {
return Promise.reject(new Error('Should match redirect uri: ' + uri))
}
var queryIndex = uri.indexOf('?')
var fragmentIndex = uri.indexOf('#')
if (queryIndex === -1) {
return Promise.reject(new Error('Unable to process uri: ' + uri))
}
var endIndex = fragmentIndex === -1 ? uri.length : fragmentIndex
var data = decodeQuery(uri.slice(queryIndex + 1, endIndex))
var err = getAuthError(data)
if (err) {
return Promise.reject(err)
}
if (state && data.state !== state) {
return Promise.reject(new Error('Invalid state:' + data.state))
}
// Check whether the response code is set.
if (!data.code) {
return Promise.reject(new Error('Missing code, unable to request token'))
}
return this.client._request({
url: options.accessTokenUri,
method: 'POST',
headers: {
'Accept': 'application/json, application/x-www-form-urlencoded',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: {
code: data.code,
grant_type: 'authorization_code',
redirect_uri: options.redirectUri,
client_id: options.clientId,
client_secret: options.clientSecret
}
})
.then(handleAuthResponse)
.then(function (data) {
return new ClientOAuth2Token(self.client, data)
})
}
/**
* Support JSON Web Token (JWT) Bearer Token OAuth 2.0 grant.
*
* Reference: https://tools.ietf.org/html/draft-ietf-oauth-jwt-bearer-12#section-2.1
*
* @param {ClientOAuth2} client
*/
function JwtBearerFlow (client) {
this.client = client
}
/**
* Request an access token using a JWT token.
*
* @param {string} token A JWT token.
* @param {Object} [options]
* @return {Promise}
*/
JwtBearerFlow.prototype.getToken = function (token, options) {
var self = this
options = assign({}, this.client.options, options)
expects(options, [
'accessTokenUri'
])
var headers = {
'Accept': 'application/json, application/x-www-form-urlencoded',
'Content-Type': 'application/x-www-form-urlencoded'
}
// Authentication of the client is optional, as described in Section 3.2.1 of OAuth 2.0 [RFC6749]
if (options.clientId) {
headers['Authorization'] = auth(options.clientId, options.clientSecret)
}
return this.client._request({
url: options.accessTokenUri,
method: 'POST',
headers: headers,
body: {
scope: sanitizeScope(options.scopes),
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion: token
}
})
.then(handleAuthResponse)
.then(function (data) {
return new ClientOAuth2Token(self.client, data)
})
}
return ClientOAuth2
})