msiAppServiceTokenCredentials.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. // Copyright (c) Microsoft Corporation. All rights reserved.
  2. // Licensed under the MIT License. See License.txt in the project root for license information.
  3. import { MSITokenCredentials, MSIOptions, MSITokenResponse } from "./msiTokenCredentials";
  4. import { HttpOperationResponse, RequestPrepareOptions, WebResource } from "@azure/ms-rest-js";
  5. /**
  6. * @interface MSIAppServiceOptions Defines the optional parameters for authentication with MSI for AppService.
  7. */
  8. export interface MSIAppServiceOptions extends MSIOptions {
  9. /**
  10. * @property {string} [msiEndpoint] - The local URL from which your app can request tokens.
  11. * Either provide this parameter or set the environment variable `MSI_ENDPOINT`.
  12. * For example: `export MSI_ENDPOINT="http://127.0.0.1:41741/MSI/token/"`
  13. */
  14. msiEndpoint?: string;
  15. /**
  16. * @property {string} [msiSecret] - The secret used in communication between your code and the local MSI agent.
  17. * Either provide this parameter or set the environment variable `MSI_SECRET`.
  18. * For example: `export MSI_SECRET="69418689F1E342DD946CB82994CDA3CB"`
  19. */
  20. msiSecret?: string;
  21. /**
  22. * @property {string} [msiApiVersion] - The api-version of the local MSI agent. Default value is "2017-09-01".
  23. */
  24. msiApiVersion?: string;
  25. }
  26. /**
  27. * @class MSIAppServiceTokenCredentials
  28. */
  29. export class MSIAppServiceTokenCredentials extends MSITokenCredentials {
  30. /**
  31. * @property {string} msiEndpoint - The local URL from which your app can request tokens.
  32. * Either provide this parameter or set the environment variable `MSI_ENDPOINT`.
  33. * For example: `MSI_ENDPOINT="http://127.0.0.1:41741/MSI/token/"`
  34. */
  35. msiEndpoint: string;
  36. /**
  37. * @property {string} msiSecret - The secret used in communication between your code and the local MSI agent.
  38. * Either provide this parameter or set the environment variable `MSI_SECRET`.
  39. * For example: `MSI_SECRET="69418689F1E342DD946CB82994CDA3CB"`
  40. */
  41. msiSecret: string;
  42. /**
  43. * @property {string} [msiApiVersion] The api-version of the local MSI agent. Default value is "2017-09-01".
  44. */
  45. msiApiVersion?: string;
  46. /**
  47. * Creates an instance of MSIAppServiceTokenCredentials.
  48. * @param {string} [options.msiEndpoint] - The local URL from which your app can request tokens.
  49. * Either provide this parameter or set the environment variable `MSI_ENDPOINT`.
  50. * For example: `MSI_ENDPOINT="http://127.0.0.1:41741/MSI/token/"`
  51. * @param {string} [options.msiSecret] - The secret used in communication between your code and the local MSI agent.
  52. * Either provide this parameter or set the environment variable `MSI_SECRET`.
  53. * For example: `MSI_SECRET="69418689F1E342DD946CB82994CDA3CB"`
  54. * @param {string} [options.resource] - The resource uri or token audience for which the token is needed.
  55. * For e.g. it can be:
  56. * - resource management endpoint "https://management.azure.com/" (default)
  57. * - management endpoint "https://management.core.windows.net/"
  58. * @param {string} [options.msiApiVersion] - The api-version of the local MSI agent. Default value is "2017-09-01".
  59. */
  60. constructor(options?: MSIAppServiceOptions) {
  61. if (!options) options = {};
  62. super(options);
  63. options.msiEndpoint = options.msiEndpoint || process.env["MSI_ENDPOINT"];
  64. options.msiSecret = options.msiSecret || process.env["MSI_SECRET"];
  65. if (!options.msiEndpoint || (options.msiEndpoint && typeof options.msiEndpoint.valueOf() !== "string")) {
  66. throw new Error('Either provide "msiEndpoint" as a property of the "options" object ' +
  67. 'or set the environment variable "MSI_ENDPOINT" and it must be of type "string".');
  68. }
  69. if (!options.msiSecret || (options.msiSecret && typeof options.msiSecret.valueOf() !== "string")) {
  70. throw new Error('Either provide "msiSecret" as a property of the "options" object ' +
  71. 'or set the environment variable "MSI_SECRET" and it must be of type "string".');
  72. }
  73. if (!options.msiApiVersion) {
  74. options.msiApiVersion = "2017-09-01";
  75. } else if (typeof options.msiApiVersion.valueOf() !== "string") {
  76. throw new Error("msiApiVersion must be a uri.");
  77. }
  78. this.msiEndpoint = options.msiEndpoint;
  79. this.msiSecret = options.msiSecret;
  80. this.msiApiVersion = options.msiApiVersion;
  81. }
  82. /**
  83. * Prepares and sends a GET request to a service endpoint indicated by the app service, which responds with the access token.
  84. * @return {Promise<MSITokenResponse>} Promise with the tokenResponse (tokenType and accessToken are the two important properties).
  85. */
  86. async getToken(): Promise<MSITokenResponse> {
  87. const reqOptions = this.prepareRequestOptions();
  88. let opRes: HttpOperationResponse;
  89. let result: MSITokenResponse;
  90. opRes = await this._httpClient.sendRequest(reqOptions);
  91. if (opRes.bodyAsText === undefined || opRes.bodyAsText!.indexOf("ExceptionMessage") !== -1) {
  92. throw new Error(`MSI: Failed to retrieve a token from "${reqOptions.url}" with an error: ${opRes.bodyAsText}`);
  93. }
  94. result = this.parseTokenResponse(opRes.bodyAsText!) as MSITokenResponse;
  95. if (!result.tokenType) {
  96. throw new Error(`Invalid token response, did not find tokenType. Response body is: ${opRes.bodyAsText}`);
  97. } else if (!result.accessToken) {
  98. throw new Error(`Invalid token response, did not find accessToken. Response body is: ${opRes.bodyAsText}`);
  99. }
  100. return result;
  101. }
  102. protected prepareRequestOptions(): WebResource {
  103. const endpoint = this.msiEndpoint.endsWith("/") ? this.msiEndpoint : `${this.msiEndpoint}/`;
  104. const resource = encodeURIComponent(this.resource);
  105. const getUrl = `${endpoint}?resource=${resource}&api-version=${this.msiApiVersion}`;
  106. const reqOptions: RequestPrepareOptions = {
  107. url: getUrl,
  108. headers: {
  109. "secret": this.msiSecret
  110. },
  111. method: "GET"
  112. };
  113. const webResource = new WebResource();
  114. return webResource.prepare(reqOptions);
  115. }
  116. }