Code coverage report for lib\token-request.js

Statements: 96.04% (218 / 227)      Branches: 88.64% (39 / 44)      Functions: 97.62% (41 / 42)      Lines: 96.04% (218 / 227)      Ignored: none     

All files » lib/ » token-request.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                                            1 1 1 1 1 1 1 1   1 1 1 1 1 1                       1 54 54 54 54 54 54       54   54 54     1 12     1 1     1 1     1 40     1 3     1 40 40     1 3 3 3     1 42                               1 4 4 4     1 42       42 26   16     42       1 42 42 42 42 42       42 35 35 35 13 13 13     22 22 22       7 7                         1 129 81                     1 43 43   43     15     43 43 43   43                   1 11   11   11 11   11                 1 5 5   3   1   1                   1 5   5 5 5 4 4 4   1 1   4                   1 8 8 8 8 1 1     7 2 2 2     5                     1 8 8 8 3 3     5               1                   1 8   8 8 4   4         4 4   4 4 4 4 4 4 1   1 1         3     4 4                         1 24   24 24 20 20 20 20         20   11 11   8 8   1                       1 14   14 13   13   13                     1 1 1   1 1   1                   1 10 10   10 3     10 2     10   10                 1 6               1 3 3   3 3       1                     1 3 3 3 1       1                   1   3   3   3 3 3   2 1     1 1 1   1 1       1 3   3 3   3 3   3     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 constants = require('./constants');
var CacheDriver = require('./cache-driver');
var Logger = require('./log').Logger;
var Mex = require('./mex');
var OAuth2Client = require('./oauth2client');
var SelfSignedJwt = require('./self-signed-jwt');
var UserRealm = require('./user-realm');
var WSTrustRequest = require('./wstrust-request');
 
var OAuth2Parameters = constants.OAuth2.Parameters;
var TokenResponseFields = constants.TokenResponseFields;
var OAuth2GrantType = constants.OAuth2.GrantType;
var OAuth2Scope = constants.OAuth2.Scope;
var Saml = constants.Saml;
var AccountType = constants.UserRealm.AccountType;
 
/**
 * Constructs a new TokenRequest object.
 * @constructor
 * @private
 * @param {object} callContext Contains any context information that applies to the request.
 * @param {AuthenticationContext} authenticationContext
 * @param {string} resource
 * @param {string} clientId
 * @param {string} redirectUri
 */
function TokenRequest(callContext, authenticationContext, clientId, resource, redirectUri) {
  this._log = new Logger('TokenRequest', callContext._logContext);
  this._callContext = callContext;
  this._authenticationContext = authenticationContext;
  this._resource = resource;
  this._clientId = clientId;
  this._redirectUri = redirectUri;
 
  // This should be set at the beginning of getToken
  // functions that have a userId.
  this._userId = null;
 
  this._userRealm = null;
  this._pollingClient = {};
}
 
TokenRequest.prototype._createUserRealmRequest = function(username) {
  return new UserRealm(this._callContext, username, this._authenticationContext.authority);
};
 
TokenRequest.prototype._createMex = function(mexEndpoint) {
  return new Mex(this._callContext, mexEndpoint);
};
 
TokenRequest.prototype._createWSTrustRequest = function(wstrustEndpoint, appliesTo) {
  return new WSTrustRequest(this._callContext, wstrustEndpoint, appliesTo);
};
 
TokenRequest.prototype._createOAuth2Client = function() {
  return new OAuth2Client(this._callContext, this._authenticationContext._authority);
};
 
TokenRequest.prototype._createSelfSignedJwt = function() {
  return new SelfSignedJwt(this._callContext, this._authenticationContext._authority, this._clientId);
};
 
TokenRequest.prototype._oauthGetToken = function(oauthParameters, callback) {
  var client = this._createOAuth2Client();
  client.getToken(oauthParameters, callback);
};
 
TokenRequest.prototype._oauthGetTokenByPolling = function(oauthParameters, refresh_interval, expires_in, callback){
  var client = this._createOAuth2Client();
  client.getTokenWithPolling(oauthParameters, refresh_interval, expires_in, callback);
  this._pollingClient = client;
}
 
TokenRequest.prototype._createCacheDriver = function() {
  return new CacheDriver(
    this._callContext,
    this._authenticationContext.authority,
    this._resource,
    this._clientId,
    this._authenticationContext.cache,
    this._getTokenWithTokenResponse.bind(this)
    );
};
 
/**
 * Used by the cache driver to refresh tokens.
 * @param  {TokenResponse}   entry    A token response to refresh.
 * @param  {string}   resource The resource for which to get the token.
 * @param  {AcquireTokenCallback} callback
 */
TokenRequest.prototype._getTokenWithTokenResponse = function(entry, resource, callback) {
  this._log.verbose('Called to refresh a token from the cache.');
  var refreshToken = entry[TokenResponseFields.REFRESH_TOKEN];
  this._getTokenWithRefreshToken(refreshToken, resource, null, callback);
};
 
TokenRequest.prototype._createCacheQuery = function() {
  var query = {
    clientId : this._clientId
  };
 
  if (this._userId) {
    query.userId = this._userId;
  } else {
    this._log.verbose('No userId passed for cache query.');
  }
 
  return query;
};
 
 
TokenRequest.prototype._getTokenWithCacheWrapper = function(callback, getTokenFunc) {
  var self = this;
  this._cacheDriver = this._createCacheDriver();
  var cacheQuery = this._createCacheQuery();
  this._cacheDriver.find(cacheQuery, function(err, token) {
    Iif (err) {
      self._log.warn('Attempt to look for token in cache resulted in Error: ' + err.stack);
    }
 
    if (!token) {
      self._log.verbose('No appropriate cached token found.');
      getTokenFunc.call(self, function(err, tokenResponse) {
        if (err) {
          self._log.verbose('getTokenFunc returned with err');
          callback(err, tokenResponse);
          return;
        }
 
        self._log.verbose('Successfully retrieved token from authority');
        self._cacheDriver.add(tokenResponse, function() {
          callback(null, tokenResponse);
        });
      });
    } else {
      self._log.info('Returning cached token.');
      callback(err, token);
    }
  });
};
 
/**
 * Adds an OAuth parameter to the paramters object if the parameter is
 * not null or undefined.
 * @private
 * @param {object} parameters  OAuth parameters object.
 * @param {string} key         A member of the OAuth2Parameters constants.
 * @param {object} value
 */
function _addParameterIfAvailable(parameters, key, value) {
  if (value) {
    parameters[key] = value;
  }
}
 
/**
 * Creates a set of basic, common, OAuthParameters based on values that the TokenRequest
 * was created with.
 * @private
 * @param  {string} grantType  A member of the OAuth2GrantType constants.
 * @return {object}
 */
TokenRequest.prototype._createOAuthParameters = function(grantType) {
  var oauthParameters = {};
  oauthParameters[OAuth2Parameters.GRANT_TYPE] = grantType;
 
  if (OAuth2GrantType.AUTHORIZATION_CODE !== grantType &&
    OAuth2GrantType.CLIENT_CREDENTIALS !== grantType &&
    OAuth2GrantType.REFRESH_TOKEN !== grantType && OAuth2GrantType.DEVICE_CODE != grantType) {
    oauthParameters[OAuth2Parameters.SCOPE] = OAuth2Scope.OPENID;
  }
 
  _addParameterIfAvailable(oauthParameters, OAuth2Parameters.CLIENT_ID, this._clientId);
  _addParameterIfAvailable(oauthParameters, OAuth2Parameters.RESOURCE, this._resource);
  _addParameterIfAvailable(oauthParameters, OAuth2Parameters.REDIRECT_URI, this._redirectUri);
 
  return oauthParameters;
};
 
/**
 * Get's a token from AAD using a username and password
 * @private
 * @param  {string}   username
 * @param  {string}   password
 * @param  {AcquireTokenCallback} callback
 */
TokenRequest.prototype._getTokenUsernamePasswordManaged = function(username, password, callback) {
  this._log.verbose('Acquiring token with username password for managed user');
 
  var oauthParameters = this._createOAuthParameters(OAuth2GrantType.PASSWORD);
 
  oauthParameters[OAuth2Parameters.PASSWORD] = password;
  oauthParameters[OAuth2Parameters.USERNAME] = username;
 
  this._oauthGetToken(oauthParameters, callback);
};
 
/**
 * Determines the OAuth SAML grant type to use based on the passed in TokenType
 * that was returned from a RSTR.
 * @param  {string} wstrustResponse RSTR token type.
 * @return {string}                 An OAuth grant type.
 */
TokenRequest.prototype._getSamlGrantType = function(wstrustResponse) {
  var tokenType = wstrustResponse.tokenType;
  switch (tokenType) {
    case Saml.TokenTypeV1:
      return OAuth2GrantType.SAML1;
    case Saml.TokenTypeV2:
      return OAuth2GrantType.SAML2;
    default:
      throw this._log.createError('RSTR returned unknown token type: ' + tokenType);
  }
};
 
/**
 * Performs an OAuth SAML Assertion grant type exchange.  Uses a SAML token as the credential for getting
 * an OAuth access token.
 * @param  {WSTrustResponse}   wstrustResponse A response from a WSTrustRequest
 * @param  {AcquireTokenCallback} callback        callback
 */
TokenRequest.prototype._performWSTrustAssertionOAuthExchange = function(wstrustResponse, callback) {
  this._log.verbose('Performing OAuth assertion grant type exchange.');
 
  var oauthParameters;
  try {
    var grantType = this._getSamlGrantType(wstrustResponse);
    var assertion = new Buffer(wstrustResponse.token).toString('base64');
    oauthParameters = this._createOAuthParameters(grantType);
    oauthParameters[OAuth2Parameters.ASSERTION] = assertion;
  } catch (err) {
    callback(err);
    return;
  }
  this._oauthGetToken(oauthParameters, callback);
};
 
/**
 * Exchange a username and password for a SAML token from an ADFS instance via WSTrust.
 * @param  {string}   wstrustEndpoint An url of an ADFS WSTrust endpoint.
 * @param  {string}   username        username
 * @param  {string}   password        password
 * @param  {AcquireTokenCallback} callback        callback
 */
TokenRequest.prototype._performWSTrustExchange = function(wstrustEndpoint, username, password, callback) {
  var self = this;
  var wstrust = this._createWSTrustRequest(wstrustEndpoint, 'urn:federation:MicrosoftOnline');
  wstrust.acquireToken(username, password, function(rstErr, response) {
    if (rstErr) {
      callback(rstErr);
      return;
    }
 
    if (!response.token) {
      var rstrErr = self._log.createError('Unsucessful RSTR.\n\terror code: ' + response.errorCode + '\n\tfaultMessage: ' + response.faultMessage);
      callback(rstrErr);
      return;
    }
 
    callback(null, response);
  });
};
 
/**
 * Given a username and password this method invokes a WSTrust and OAuth exchange to get an access token.
 * @param  {string}   wstrustEndpoint An url of an ADFS WSTrust endpoint.
 * @param  {string}   username        username
 * @param  {string}   password        password
 * @param  {AcquireTokenCallback} callback        callback
 */
TokenRequest.prototype._performUsernamePasswordForAccessTokenExchange = function(wstrustEndpoint, username, password, callback) {
  var self = this;
  this._performWSTrustExchange(wstrustEndpoint, username, password, function(err, wstrustResponse) {
    if (err) {
      callback(err);
      return;
    }
 
    self._performWSTrustAssertionOAuthExchange(wstrustResponse, callback);
  });
};
 
/**
 * Returns an Error object indicating that AAD did not return a WSTrust endpoint.
 * @return {Error}
 */
TokenRequest.prototype._createADWSTrustEndpointError = function() {
  return this._log.createError('AAD did not return a WSTrust endpoint.  Unable to proceed.');
};
 
/**
 * Gets an OAuth access token using a username and password via a federated ADFS instance.
 * @param  {string}   username        username
 * @param  {string}   password        password
 * @param  {AcquireTokenCallback} callback        callback
 */
TokenRequest.prototype._getTokenUsernamePasswordFederated = function(username, password, callback) {
  this._log.verbose('Acquiring token with username password for federated user');
 
  var self = this;
  if (!this._userRealm.federationMetadataUrl) {
    this._log.warn('Unable to retrieve federationMetadataUrl from AAD.  Attempting fallback to AAD supplied endpoint.');
 
    Iif (!this._userRealm.federationActiveAuthUrl) {
      callback(this._createADWSTrustEndpointError());
      return;
    }
 
    this._performUsernamePasswordForAccessTokenExchange(this._userRealm.federationActiveAuthUrl, username, password, callback);
    return;
  } else {
    var mexEndpoint = this._userRealm.federationMetadataUrl;
    this._log.verbose('Attempting mex at: ' + mexEndpoint);
    var mex = this._createMex(mexEndpoint);
    mex.discover(function(mexErr) {
      var wstrustEndpoint;
      if (mexErr) {
        self._log.warn('MEX exchnage failed.  Attempting fallback to AAD supplied endpoint.');
 
        wstrustEndpoint = self._userRealm.federationActiveAuthUrl;
        Iif (!wstrustEndpoint) {
          callback(self._createADWSTrustEndpointError());
          return;
        }
      } else {
        wstrustEndpoint = mex.usernamePasswordUrl;
      }
 
      self._performUsernamePasswordForAccessTokenExchange(wstrustEndpoint, username, password, callback);
      return;
    });
  }
};
 
/**
 * Decides whether the username represents a managed or a federated user and then
 * obtains a token using the appropriate protocol flow.
 * @private
 * @param  {string}   username
 * @param  {string}   password
 * @param  {AcquireTokenCallback} callback
 */
TokenRequest.prototype.getTokenWithUsernamePassword = function(username, password, callback) {
  this._log.info('Acquiring token with username password');
 
  this._userId = username;
  this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) {
    var self = this;
    this._userRealm = this._createUserRealmRequest(username);
    this._userRealm.discover(function(err) {
      Iif (err) {
        getTokenCompleteCallback(err);
        return;
      }
 
      switch(self._userRealm.accountType) {
        case AccountType.Managed:
          self._getTokenUsernamePasswordManaged(username, password, getTokenCompleteCallback);
          return;
        case AccountType.Federated:
          self._getTokenUsernamePasswordFederated(username, password, getTokenCompleteCallback);
          return;
        default:
          getTokenCompleteCallback(self._log.createError('Server returned an unknown AccountType: ' + self._userRealm.AccountType));
      }
    });
  });
};
 
/**
 * Obtains a token using client credentials
 * @private
 * @param  {string}   clientSecret
 * @param  {AcquireTokenCallback} callback
 */
TokenRequest.prototype.getTokenWithClientCredentials = function(clientSecret, callback) {
  this._log.info('Getting token with client credentials.');
 
  this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) {
    var oauthParameters = this._createOAuthParameters(OAuth2GrantType.CLIENT_CREDENTIALS);
 
    oauthParameters[OAuth2Parameters.CLIENT_SECRET] = clientSecret;
 
    this._oauthGetToken(oauthParameters, getTokenCompleteCallback);
  });
};
 
/**
 * Obtains a token using an authorization code.
 * @private
 * @param  {string}   authorizationCode
 * @param  {string}   clientSecret
 * @param  {AcquireTokenCallback} callback
 */
TokenRequest.prototype.getTokenWithAuthorizationCode = function(authorizationCode, clientSecret, callback) {
  this._log.info('Getting token with auth code.');
  var oauthParameters = this._createOAuthParameters(OAuth2GrantType.AUTHORIZATION_CODE);
 
  oauthParameters[OAuth2Parameters.CODE] = authorizationCode;
  oauthParameters[OAuth2Parameters.CLIENT_SECRET] = clientSecret;
 
  this._oauthGetToken(oauthParameters, callback);
};
 
/**
 * Obtains a token using a refresh token.
 * @param  {string}   refreshToken
 * @param  {string}   resource
 * @param  {string}   [clientSecret]
 * @param  {AcquireTokenCallback} callback
 */
TokenRequest.prototype._getTokenWithRefreshToken = function(refreshToken, resource, clientSecret, callback) {
  this._log.info('Getting a new token from a refresh token.');
  var oauthParameters = this._createOAuthParameters(OAuth2GrantType.REFRESH_TOKEN);
 
  if (resource) {
    oauthParameters[OAuth2Parameters.RESOURCE] = resource;
  }
 
  if (clientSecret) {
    oauthParameters[OAuth2Parameters.CLIENT_SECRET] = clientSecret;
  }
 
  oauthParameters[OAuth2Parameters.REFRESH_TOKEN] = refreshToken;
 
  this._oauthGetToken(oauthParameters, callback);
};
 
/**
 * Obtains a token using a refresh token.
 * @param  {string}   refreshToken
 * @param  {string}   [clientSecret]
 * @param  {AcquireTokenCallback} callback
 */
TokenRequest.prototype.getTokenWithRefreshToken = function(refreshToken, clientSecret, callback) {
  this._getTokenWithRefreshToken(refreshToken, null, clientSecret, callback);
};
 
/**
 * Obtains a token from the cache, refreshing it or using a MRRT if necessary.
 * @param {string}  [userId] The user associated with the cached token.
 * @param  {AcquireTokenCallback} callback
 */
TokenRequest.prototype.getTokenFromCacheWithRefresh = function(userId, callback) {
  var self = this;
  this._log.info('Getting token from cache with refresh if necessary.');
 
  this._userId = userId;
  this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) {
    // If this method was called then no cached entry was found.  Since
    // this particular version of acquireToken can only retrieve tokens
    // from the cache, return an error.
    getTokenCompleteCallback(self._log.createError('Entry not found in cache.'));
  });
};
 
/**
 * Creates a self signed jwt.
 * @param  {string} authorityUrl
 * @param  {string} certificate  A PEM encoded certificate private key.
 * @param  {string} thumbprint
 * @return {string}              A self signed JWT
 */
TokenRequest.prototype._createJwt = function(authorityUrl, certificate, thumbprint) {
  var jwt;
  var ssj = this._createSelfSignedJwt();
  jwt = ssj.create(certificate, thumbprint);
  Iif (!jwt) {
    throw this._log.createError('Failed to create JWT');
  }
 
  return jwt;
};
 
/**
 * Obtains a token via a certificate.  The certificate is used to generate a self signed
 * JWT token that is passed as a client_assertion.
 * @param  {string}                 certificate   A PEM encoded certificate private key.
 * @param  {string}                 thumbprint    A hex encoded thumbprint of the certificate.
 * @param  {AcquireTokenCallback}   callback
 */
TokenRequest.prototype.getTokenWithCertificate = function(certificate, thumbprint, callback) {
 
  this._log.info('Getting a token via certificate.');
 
  var authorityUrl = this._authenticationContext._authority;
 
  var jwt;
  try {
    jwt = this._createJwt(authorityUrl, certificate, thumbprint);
  } catch (err) {
    callback(err);
    return;
  }
 
  var oauthParameters = this._createOAuthParameters(OAuth2GrantType.CLIENT_CREDENTIALS);
  oauthParameters[OAuth2Parameters.CLIENT_ASSERTION_TYPE] = OAuth2GrantType.JWT_BEARER;
  oauthParameters[OAuth2Parameters.CLIENT_ASSERTION] = jwt;
 
  this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) {
    this._oauthGetToken(oauthParameters, getTokenCompleteCallback);
  });
};
 
TokenRequest.prototype.getTokenWithDeviceCode = function(userCodeInfo, callback) {
   this._log.info('Getting a token via device code');
 
   var oauthParameters = this._createOAuthParameters(OAuth2GrantType.DEVICE_CODE);
   oauthParameters[OAuth2Parameters.CODE] = userCodeInfo[OAuth2Parameters.DEVICE_CODE];
 
   var interval = userCodeInfo[constants.OAuth2.DeviceCodeResponseParameters.INTERVAL];
   var expires_in = userCodeInfo[constants.OAuth2.DeviceCodeResponseParameters.EXPIRES_IN];
 
   this._oauthGetTokenByPolling(oauthParameters, interval, expires_in, callback);
};
 
TokenRequest.prototype.cancelTokenRequestWithDeviceCode = function() {
    this._pollingClient.cancelPollingRequest();
};
 
module.exports = TokenRequest;