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 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 49 49 49 49 49 1 40 40 40 40 40 40 1 2 2 2 2 2 2 1 37 37 108 73 73 1 1 45 45 45 11 11 34 34 1 30 30 30 30 30 30 30 30 30 30 30 1 66 628 296 296 1 30 30 30 30 1 32 32 1 31 31 31 31 31 31 1 1 30 1 36 36 36 36 1 35 35 34 34 34 34 34 34 34 34 34 34 1 33 1 32 32 32 32 30 32 1 2 2 2 2 2 2 2 2 2 2 2 1 4 4 2 4 1 4 4 4 4 4 2 4 1 34 34 34 4 4 4 30 1 2 2 2 2 1 5 5 1 1 4 4 4 4 4 2 2 1 42 42 1 37 37 37 37 37 34 1 3 3 3 3 3 3 3 5 3 1 2 2 2 2 2 2 1 1 1 | /* * @copyright * Copyright © Microsoft Open Technologies, Inc. * * All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http: *www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. * * See the Apache License, Version 2.0 for the specific language * governing permissions and limitations under the License. */ 'use strict'; var _ = require('underscore'); require('date-utils'); // Adds a number of convenience methods to the builtin Date object. var querystring = require('querystring'); var uuid = require('node-uuid'); var request = require('request'); var url = require('url'); var async = require('async'); var constants = require('./constants'); var Logger = require('./log').Logger; var util = require('./util'); var OAuth2Parameters = constants.OAuth2.Parameters; var OAuth2ResponseParameters = constants.OAuth2.ResponseParameters; var DeviceCodeResponseParameters = constants.OAuth2.DeviceCodeResponseParameters; var IdTokenMap = constants.OAuth2.IdTokenMap; var TokenResponseFields = constants.TokenResponseFields; var UserCodeResponseFields = constants.UserCodeResponseFields; var IdTokenFields = constants.IdTokenFields; var TOKEN_RESPONSE_MAP = {}; TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.TOKEN_TYPE] = TokenResponseFields.TOKEN_TYPE; TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ACCESS_TOKEN] = TokenResponseFields.ACCESS_TOKEN; TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.REFRESH_TOKEN] = TokenResponseFields.REFRESH_TOKEN; TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.CREATED_ON] = TokenResponseFields.CREATED_ON; TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.EXPIRES_ON] = TokenResponseFields.EXPIRES_ON; TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.EXPIRES_IN] = TokenResponseFields.EXPIRES_IN; TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.RESOURCE] = TokenResponseFields.RESOURCE; TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ERROR] = TokenResponseFields.ERROR; TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ERROR_DESCRIPTION] = TokenResponseFields.ERROR_DESCRIPTION; var DEVICE_CODE_RESPONSE_MAP = {}; DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.DEVICE_CODE] = UserCodeResponseFields.DEVICE_CODE; DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.USER_CODE] = UserCodeResponseFields.USER_CODE; DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.VERIFICATION_URL] = UserCodeResponseFields.VERIFICATION_URL; DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.INTERVAL] = UserCodeResponseFields.INTERVAL; DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.EXPIRES_IN] = UserCodeResponseFields.EXPIRES_IN; DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.MESSAGE] = UserCodeResponseFields.MESSAGE; DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.ERROR] = UserCodeResponseFields.ERROR; DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.ERROR_DESCRIPTION] = UserCodeResponseFields.ERROR_DESCRIPTION; /** * Constructs an instances of OAuth2Client * @constructor * @private * @param {object} callContext Contains any context information that applies to the request. * @param {string|url} authority An url that points to an authority. */ function OAuth2Client(callContext, authority) { this._tokenEndpoint = authority.tokenEndpoint; this._deviceCodeEndpoint = authority.deviceCodeEndpoint; this._log = new Logger('OAuth2Client', callContext._logContext); this._callContext = callContext; this._cancelPollingRequest = false; } /** * Constructs an OAuth 2.0 token request url. * @private * @return {URL} */ OAuth2Client.prototype._createTokenUrl = function () { var tokenUrl = url.parse(this._tokenEndpoint); var parameters = {}; parameters.slice = 'testslice'; parameters[OAuth2Parameters.AAD_API_VERSION] = '1.0'; tokenUrl.search = querystring.stringify(parameters); return tokenUrl; }; OAuth2Client.prototype._createDeviceCodeUrl = function () { var deviceCodeUrl = url.parse(this._deviceCodeEndpoint); var parameters = {}; parameters.slice = 'testslice'; parameters[OAuth2Parameters.AAD_API_VERSION] = '1.0'; deviceCodeUrl.search = querystring.stringify(parameters); return deviceCodeUrl; }; /** * @private * @param {object} obj An object in which integer values may reside. * @param {array} keys An array of strings that specify keys in which integers may need parsing. */ OAuth2Client.prototype._parseOptionalInts = function (obj, keys) { var self = this; keys.forEach(function(element) { if (_.has(obj, element)) { obj[element] = parseInt(obj[element], 10); if (isNaN(obj[element])) { throw self._log.createError(element + ' could not be parsed as an int.'); } } }); }; /** * Cracks a JWS encoded JWT into it's three parts. * @param {string} jwtToken The token to crack. * @return {object} The three JWS parts, header, JWSPayload, and JWSSig, or undefined. */ OAuth2Client.prototype._crackJwt = function(jwtToken) { var idTokenPartsRegex = /^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/; var matches = idTokenPartsRegex.exec(jwtToken); if (!matches || matches.length < 4) { this._log.warn('The returned id_token is not parseable.'); return; } var crackedToken = { header : matches[1], JWSPayload : matches[2], JWSSig : matches[3] }; return crackedToken; }; /** * Finds the value that should be used as the userId value. * @param {object} idToken The id token that parsed. * @returns {object} An object with a userId field and maybe a userIdIsDisplayable field. */ OAuth2Client.prototype._getUserId = function(idToken) { var userId; var isDisplayable; Eif (idToken.upn) { userId = idToken.upn; isDisplayable = true; } else if (idToken.email) { userId = idToken.email; isDisplayable = true; } else if (idToken.subject) { userId = idToken.subject; } Iif (!userId) { // generate a random GUID. userId = uuid.v4(); } var userIdVals = {}; userIdVals[IdTokenFields.USER_ID] = userId; Eif (isDisplayable) { userIdVals[IdTokenFields.IS_USER_ID_DISPLAYABLE] = true; } return userIdVals; }; function mapFields(inObj, outObj, map) { for (var key in inObj) { if (map[key]) { var mappedKey = map[key]; outObj[mappedKey] = inObj[key]; } } } /** * Given a decoded id token off the wire, this function extracts the values that * ADAL commonly returns to callers and translates the names to more user * friendly names. * @param {Object} idToken A decoded id token. * @return {Object} The set of extracted values with their new names. */ OAuth2Client.prototype._extractIdTokenValues = function(idToken) { var extractedValues = {}; _.extend(extractedValues, this._getUserId(idToken)); mapFields(idToken, extractedValues, IdTokenMap); return extractedValues; }; /** * Parses the value of the id_token OAuth 2 Reponse. * @param {string} encodedIdToken An unencrypted JWT token. * @return {object} returns the decoded id_token or undefined. */ OAuth2Client.prototype._parseIdToken = function(encodedIdToken) { var crackedToken = this._crackJwt(encodedIdToken); if (!crackedToken) { return; } var idToken; try { var base64IdToken = crackedToken.JWSPayload; var base64Decoded = util.base64DecodeStringUrlSafe(base64IdToken); Iif (!base64Decoded) { this._log.warn('The returned id_token could not be base64 url safe decoded.'); return; } idToken = JSON.parse(base64Decoded); } catch(err) { this._log.warn('The returned id_token could not be decoded: ' + err.stack); return; } return this._extractIdTokenValues(idToken); }; /** * Validates the response returned from an OAuth 2.0 token request. * @private * @param {string} body The response as a string encoded JSON object. * @return {object} The parsed response. */ OAuth2Client.prototype._validateTokenResponse = function(body) { var wireResponse; var tokenResponse = {}; try { wireResponse = JSON.parse(body); } catch(e) { throw new Error('The token response returned from the server is unparseable as JSON'); } var intKeys = [ OAuth2ResponseParameters.EXPIRES_ON, OAuth2ResponseParameters.EXPIRES_IN, OAuth2ResponseParameters.CREATED_ON ]; this._parseOptionalInts(wireResponse, intKeys); Eif (wireResponse[OAuth2ResponseParameters.EXPIRES_IN]) { var expiresIn = wireResponse[OAuth2ResponseParameters.EXPIRES_IN]; var now = new Date(); wireResponse[OAuth2ResponseParameters.EXPIRES_ON] = now.add( { seconds : expiresIn }); } Eif (wireResponse[OAuth2ResponseParameters.CREATED_ON]) { var tempDate = new Date(); var createdOn = wireResponse[OAuth2ResponseParameters.CREATED_ON]; tempDate.setTime(createdOn); wireResponse[OAuth2ResponseParameters.CREATED_ON] = tempDate; } if (!wireResponse[OAuth2ResponseParameters.TOKEN_TYPE]) { throw this._log.createError('wireResponse is missing token_type'); } if (!wireResponse[OAuth2ResponseParameters.ACCESS_TOKEN]) { throw this._log.createError('wireResponse missing access_token'); } mapFields(wireResponse, tokenResponse, TOKEN_RESPONSE_MAP); Eif (wireResponse[OAuth2ResponseParameters.ID_TOKEN]) { var idToken = this._parseIdToken(wireResponse[OAuth2ResponseParameters.ID_TOKEN]); if (idToken) { _.extend(tokenResponse, idToken); } } return tokenResponse; }; /** * Validates the response returned from an OAuth 2.0 device code request. * @private * @param {string} body The response as a string encoded JSON object. * @return {object} The parsed response. */ OAuth2Client.prototype._validateDeviceCodeResponse = function(body) { var wireResponse; var deviceCodeResponse = {}; try { wireResponse = JSON.parse(body); } catch(e) { throw new Error('The device code response returned from the server is unparseable as JSON.'); } var intKeys = [ DeviceCodeResponseParameters.EXPIRES_IN, DeviceCodeResponseParameters.INTERVAL ]; this._parseOptionalInts(wireResponse, intKeys); Iif (!wireResponse[DeviceCodeResponseParameters.EXPIRES_IN]){ throw this._log.createError('wireResponse is missing expires_in'); } Iif (!wireResponse[DeviceCodeResponseParameters.DEVICE_CODE]) { throw this._log.createError('wireResponse is missing device code'); } Iif (!wireResponse[DeviceCodeResponseParameters.USER_CODE]) { throw this._log.createError('wireResponse is missing user code'); } mapFields(wireResponse, deviceCodeResponse, DEVICE_CODE_RESPONSE_MAP); return deviceCodeResponse; }; /** * @private * @param {string} body The body of a http token response. * @param {OAuth2Client.GetTokenCallback} callback A call back function. The body parameter is the body parameter passed * into this function. */ OAuth2Client.prototype._handlePollingResponse = function(body) { //handle token error response var tokenResponse = this._handlePollingRequestErrorResponse(body); if (_.isEmpty(tokenResponse)){ tokenResponse = this._validateTokenResponse(body); } return tokenResponse; }; /** * @private * @param {string} body The body of a http token response. * @param {OAuth2Client.GetTokenCallback} callback A call back function. The body parameter is the body parameter passed * into this function. */ OAuth2Client.prototype._handlePollingRequestErrorResponse = function(body) { var wireResponse; var tokenResponse = {}; try { wireResponse = JSON.parse(body); } catch (e) { throw new Error ('The token response returned from the server is unparsable as JSON'); } if (wireResponse[OAuth2ResponseParameters.ERROR]) { mapFields(wireResponse, tokenResponse, TOKEN_RESPONSE_MAP); } return tokenResponse; }; /** * @private * @param {object} response An http response object. * @param {string} body The body of a http token response. * @param {OAuth2Client.GetTokenCallback} callback A call back function. The body parameter is the body parameter passed * into this function. */ OAuth2Client.prototype._handleGetTokenResponse = function(response, body, callback) { var tokenResponse; try { tokenResponse = this._validateTokenResponse(body); } catch (e) { this._log.error('Error validating get token response', e); callback(e); return; } callback(null, tokenResponse); }; OAuth2Client.prototype._handleGetDeviceCodeResponse = function(response, body, callback) { var deviceCodeResponse; try { deviceCodeResponse = this._validateDeviceCodeResponse(body); } catch (e) { this._log.error('Error validating get user code response', e); callback(e); return; } callback(null, deviceCodeResponse); }; OAuth2Client.prototype._getTokenWithPolling = function (postOptions, callback) { var self = this; if (self._cancelPollingRequest === true) { callback(null, 'polling request is cancelled'); return; } request.post(postOptions, util.createRequestHandler('Get Token', this._log, callback, function (response, body) { var tokenResponse; try { tokenResponse = self._handlePollingResponse(body); } catch (e) { self._log.error('Error validating get token response', e); callback(null, e); return; } // TODO: double check for the returned error // If the error is invalid request or success response, return the response // else retry if (tokenResponse.hasOwnProperty(TokenResponseFields.ERROR) && tokenResponse[TokenResponseFields.ERROR] === 'authorization_pending') { callback(new Error(tokenResponse[TokenResponseFields.ERROR]), tokenResponse); } else { callback(null, tokenResponse); } }) ); }; OAuth2Client.prototype._createPostOption = function (postUrl, urlEncodedRequestForm) { var postOptions = util.createRequestOptions( this, { 'url' : postUrl, body : urlEncodedRequestForm, headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, followRedirect : false, encoding : 'utf8' } ); return postOptions; }; /** * @callback GetTokenCallback * @memberOf OAuth2Client * @param {Error} [error] In case of an error this will hold the associated Error object. * @param {TokenResponse} tokenResponse Contains the parsed result of a get token request. */ /** * @param {object} oauthParameters An object whose keys come from * Constants.OAuth2.Parameters * @param {OAuth2Client.GetTokenCallback} callback The callback function. */ OAuth2Client.prototype.getToken = function(oauthParameters, callback) { var self = this; var tokenUrl = self._createTokenUrl(); var urlEncodedTokenRequestForm = querystring.stringify(oauthParameters); var postOptions = self._createPostOption(tokenUrl, urlEncodedTokenRequestForm); request.post(postOptions, util.createRequestHandler('Get Token', this._log, callback, function (response, body) { self._handleGetTokenResponse(response, body, callback); }) ); }; /** * @param {object} oauthParameters An object whose keys come from * Constants.OAuth2.Parameters * @param {integer} refresh_interval The interval for polling request. * @param {integer} exipres_in The timeout for polling request. * @param {OAuth2Client.GetTokenCallback} callback The callback function. */ OAuth2Client.prototype.getTokenWithPolling = function(oauthParameters, refresh_interval, expires_in, callback){ var self = this; var maxTimesForRetry = Math.floor(expires_in / refresh_interval); var tokenUrl = self._createTokenUrl(); var urlEncodedTokenRequestForm = querystring.stringify(oauthParameters); var postOptions = self._createPostOption(tokenUrl, urlEncodedTokenRequestForm); var optionsForRetry = {times: maxTimesForRetry, interval: refresh_interval * 1000}; async.retry(optionsForRetry, function(retryCallback, response) { self._getTokenWithPolling(postOptions, retryCallback); }, function(err, response) { callback(err, response); }); }; OAuth2Client.prototype.getUserCodeInfo = function(oauthParameters, callback) { // for now make it as a post request var self = this; var deviceCodeUrl = self._createDeviceCodeUrl(); var urlEncodedDeviceCodeRequestForm = querystring.stringify(oauthParameters); var postOptions = self._createPostOption(deviceCodeUrl, urlEncodedDeviceCodeRequestForm); request.post(postOptions, util.createRequestHandler('Get Device Code ', this._log, callback, function (response, body) { self._handleGetDeviceCodeResponse(response, body, callback); }) ); }; /** * Cancel the polling request made for acquiring token by device code. */ OAuth2Client.prototype.cancelPollingRequest = function() { this._cancelPollingRequest = true; }; module.exports = OAuth2Client; |