authentication-parameters.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. /*
  2. * @copyright
  3. * Copyright © Microsoft Open Technologies, Inc.
  4. *
  5. * All Rights Reserved
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http: *www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
  14. * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  15. * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
  16. * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
  17. *
  18. * See the Apache License, Version 2.0 for the specific language
  19. * governing permissions and limitations under the License.
  20. */
  21. 'use strict';
  22. var request = require('request');
  23. var argument = require('./argument');
  24. var log = require('./log');
  25. var util = require('./util');
  26. var HttpErrorCode = require('./constants').HttpError;
  27. /*
  28. * Constants
  29. */
  30. var consts = {
  31. AUTHORIZATION_URI : 'authorization_uri',
  32. RESOURCE : 'resource',
  33. WWW_AUTHENTICATE_HEADER : 'www-authenticate'
  34. };
  35. /**
  36. * The AuthenticationParameters class holds the parameters that are parsed from an OAuth challenge
  37. * in the www-authenticate header.
  38. * @constructor
  39. * @param {string} authorizationUri The URI of an authority that can issues tokens for the
  40. * resource that issued the challenge.
  41. * @param {string} resource The resource for a which a token should be requested from the authority.
  42. */
  43. function AuthenticationParameters(authorizationUri, resource) {
  44. this._authorizationUri = authorizationUri;
  45. this._resource = resource;
  46. }
  47. /**
  48. * The URI of an authority that can issues tokens for the resource that issued the challenge.
  49. * @instance
  50. * @memberOf AuthenticationParameters
  51. * @type {string}
  52. * @name authorizationUri
  53. */
  54. Object.defineProperty(AuthenticationParameters.prototype, 'authorizationUri', {
  55. get : function() {
  56. return this._authorizationUri;
  57. }
  58. });
  59. /**
  60. * The resource for a which a token should be requested from the authority.
  61. * This property may be undefined if the resource was not returned in the challenge.
  62. * @instance
  63. * @memberOf AuthenticationParameters
  64. * @type {string}
  65. * @name authorizationUri
  66. */
  67. Object.defineProperty(AuthenticationParameters.prototype, 'resource', {
  68. get : function() {
  69. return this._resource;
  70. }
  71. });
  72. var exports = {};
  73. // The 401 challenge is a standard defined in RFC6750, which is based in part on RFC2617.
  74. // The challenge has the following form.
  75. // WWW-Authenticate : Bearer authorization_uri="https://login.windows.net/mytenant.com/oauth2/authorize",Resource_id="00000002-0000-0000-c000-000000000000"
  76. // This regex is used to validate the structure of the challenge header.
  77. // Match whole structure: ^\s*Bearer\s+([^,\s="]+?)="([^"]*?)"\s*(,\s*([^,\s="]+?)="([^"]*?)"\s*)*$
  78. // ^ Start at the beginning of the string.
  79. // \s*Bearer\s+ Match 'Bearer' surrounded by one or more amount of whitespace.
  80. // ([^,\s="]+?) This cpatures the key which is composed of any characters except comma, whitespace or a quotes.
  81. // = Match the = sign.
  82. // "([^"]*?)" Captures the value can be any number of non quote characters. At this point only the first key value pair as been captured.
  83. // \s* There can be any amount of white space after the first key value pair.
  84. // ( Start a capture group to retrieve the rest of the key value pairs that are separated by commas.
  85. // \s* There can be any amount of whitespace before the comma.
  86. // , There must be a comma.
  87. // \s* There can be any amount of whitespace after the comma.
  88. // (([^,\s="]+?) This will capture the key that comes after the comma. It's made of a series of any character excpet comma, whitespace or quotes.
  89. // = Match the equal sign between the key and value.
  90. // " Match the opening quote of the value.
  91. // ([^"]*?) This will capture the value which can be any number of non quote characters.
  92. // " Match the values closing quote.
  93. // \s* There can be any amount of whitespace before the next comma.
  94. // )* Close the capture group for key value pairs. There can be any number of these.
  95. // $ The rest of the string can be whitespace but nothing else up to the end of the string.
  96. //
  97. //
  98. // In other some other languages the regex above would be all that was needed. However, in JavaScript the RegExp object does not
  99. // return all of the captures in one go. So the regex above needs to be broken up so that captures can be retrieved
  100. // iteratively.
  101. //
  102. function parseChallenge(challenge) {
  103. // This regex checks the structure of the whole challenge header. The complete
  104. // header needs to be checked for validity before we can be certain that
  105. // we will succeed in pulling out the individual parts.
  106. var bearerChallengeStructureValidation = /^\s*Bearer\s+([^,\s="]+?)="([^"]*?)"\s*(,\s*([^,\s="]+?)="([^"]*?)"\s*)*$/;
  107. // This regex pulls out the key and value from the very first pair.
  108. var firstKeyValuePairRegex = /^\s*Bearer\s+([^,\s="]+?)="([^"]*?)"\s*/;
  109. // This regex is used to pull out all of the key value pairs after the first one.
  110. // All of these begin with a comma.
  111. var allOtherKeyValuePairRegex = /(?:,\s*([^,\s="]+?)="([^"]*?)"\s*)/g;
  112. if (!bearerChallengeStructureValidation.test(challenge)) {
  113. throw new Error('The challenge is not parseable as an RFC6750 OAuth2 challenge');
  114. }
  115. var challengeParameters = {};
  116. for(var match = firstKeyValuePairRegex.exec(challenge);
  117. match;
  118. match = allOtherKeyValuePairRegex.exec(challenge)) {
  119. challengeParameters[match[1]] = match[2];
  120. }
  121. return challengeParameters;
  122. }
  123. exports.AuthenticationParameters = AuthenticationParameters;
  124. /**
  125. * Creates an {@link AuthenticationParameters} object from the contents of a
  126. * www-authenticate header received from a HTTP 401 response from a resource server.
  127. * @param {string} challenge The content fo the www-authenticate header.
  128. * @return {AuthenticationParameters} An AuthenticationParameters object containing the parsed values from the header.
  129. */
  130. exports.createAuthenticationParametersFromHeader = function(challenge) {
  131. argument.validateStringParameter(challenge, 'challenge');
  132. var challengeParameters = parseChallenge(challenge);
  133. var authorizationUri = challengeParameters[consts.AUTHORIZATION_URI];
  134. if (!authorizationUri) {
  135. throw new Error('Could not find \'authorization_uri\' in challenge header.');
  136. }
  137. var resource = challengeParameters[consts.RESOURCE];
  138. return new AuthenticationParameters(authorizationUri, resource);
  139. };
  140. /**
  141. * Create an {@link AuthenticationParameters} object from a node http.IncomingMessage
  142. * object that was created as a result of a request to a resource server. This function
  143. * expects the response to contain a HTTP 401 error code with a www-authenticate
  144. * header.
  145. * @param {http.IncomingMessage} response A response from a http request to a resource server.
  146. * @return {AuthenticationParameters}
  147. */
  148. exports.createAuthenticationParametersFromResponse = function(response) {
  149. if (!response) {
  150. throw new Error('Mising required parameter: response');
  151. }
  152. if (!response.statusCode) {
  153. throw new Error('The response parameter does not have the expected HTTP statusCode field');
  154. }
  155. if (HttpErrorCode.UNAUTHORIZED !== response.statusCode) {
  156. throw new Error('The response status code does not correspond to an OAuth challenge. ' +
  157. 'The statusCode is expected to be 401 but is: ' + response.statusCode);
  158. }
  159. if (!response.headers) {
  160. throw new Error('There were no headers found in the response.');
  161. }
  162. var challenge = response.headers[consts.WWW_AUTHENTICATE_HEADER];
  163. if (!challenge) {
  164. throw new Error('The response does not contain a WWW-Authenticate header that can be used to determine the authority_uri and resource.');
  165. }
  166. return exports.createAuthenticationParametersFromHeader(challenge);
  167. };
  168. function validateUrlObject(url) {
  169. if (!url || !url.href) {
  170. throw new Error('Parameter is of wrong type: url');
  171. }
  172. }
  173. /**
  174. * This is the callback that is passed to all acquireToken variants below.
  175. * @callback CreateAuthenticationParametersCallback
  176. * @memberOf AuthenticationContext
  177. * @param {Error} [error] If the request fails this parameter will contain an Error object.
  178. * @param {AuthenticationParameters} [parameters] On a succesful request returns a {@link AuthenticationParameters}.
  179. */
  180. /**
  181. * Creates an {@link AuthenticationParameters} object by sending a get request
  182. * to the url passed to this function, and parsing the resulting http 401
  183. * response.
  184. * @param {string|url} url The url of a resource server.
  185. * @param {AuthenticationParameters} callback Called on error or request completion.
  186. * @param {string} [correlationId] An optional correlationId to pass along with the request and to include in any logs.
  187. */
  188. exports.createAuthenticationParametersFromUrl = function(url, callback, correlationId) {
  189. argument.validateCallbackType(callback);
  190. try {
  191. if (!url) {
  192. callback(new Error('Missing required parameter: url'));
  193. return;
  194. }
  195. var challengeUrl;
  196. if ('string' === typeof(url)) {
  197. challengeUrl = url;
  198. } else {
  199. validateUrlObject(url);
  200. challengeUrl = url.href;
  201. }
  202. var logContext = log.createLogContext(correlationId);
  203. var logger = new log.Logger('AuthenticationParameters', logContext);
  204. logger.verbose('Attempting to retrieve authentication parameters');
  205. logger.verbose('Attempting to retrieve authentication parameters from: ' + challengeUrl, true);
  206. var options = util.createRequestOptions( { _callContext : { _logContext: logContext } } );
  207. request.get(challengeUrl, options, function(err, response) {
  208. if (err) {
  209. logger.error('Authentication parameters http get failed.', err, true);
  210. callback(err);
  211. return;
  212. }
  213. var parameters;
  214. try {
  215. parameters = exports.createAuthenticationParametersFromResponse(response);
  216. } catch(creationErr) {
  217. logger.error('Unable to parse response in to authentication paramaters.', creationErr, true);
  218. callback(creationErr);
  219. return;
  220. }
  221. callback(null, parameters);
  222. });
  223. } catch(err) {
  224. callback(err);
  225. return;
  226. }
  227. };
  228. module.exports = exports;