userTokenCredentials.ts 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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 { TokenCredentialsBase } from "./tokenCredentialsBase";
  4. import { Environment } from "@azure/ms-rest-azure-env";
  5. import { TokenAudience } from "../util/authConstants";
  6. import { TokenResponse, ErrorResponse, TokenCache } from "adal-node";
  7. export class UserTokenCredentials extends TokenCredentialsBase {
  8. readonly username: string;
  9. readonly password: string;
  10. /**
  11. * Creates a new UserTokenCredentials object.
  12. *
  13. * @constructor
  14. * @param {string} clientId The active directory application client id.
  15. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
  16. * for an example.
  17. * @param {string} domain The domain or tenant id containing this application.
  18. * @param {string} username The user name for the Organization Id account.
  19. * @param {string} password The password for the Organization Id account.
  20. * @param {string} [tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'.
  21. * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).
  22. * @param {Environment} [environment] The azure environment to authenticate with.
  23. * @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal.
  24. */
  25. public constructor(
  26. clientId: string,
  27. domain: string,
  28. username: string,
  29. password: string,
  30. tokenAudience?: TokenAudience,
  31. environment?: Environment,
  32. tokenCache?: TokenCache) {
  33. if (!clientId || typeof clientId.valueOf() !== "string") {
  34. throw new Error("clientId must be a non empty string.");
  35. }
  36. if (!domain || typeof domain.valueOf() !== "string") {
  37. throw new Error("domain must be a non empty string.");
  38. }
  39. if (!username || typeof username.valueOf() !== "string") {
  40. throw new Error("username must be a non empty string.");
  41. }
  42. if (!password || typeof password.valueOf() !== "string") {
  43. throw new Error("password must be a non empty string.");
  44. }
  45. super(clientId, domain, tokenAudience, environment, tokenCache);
  46. this.username = username;
  47. this.password = password;
  48. }
  49. private crossCheckUserNameWithToken(username: string, userIdFromToken: string): boolean {
  50. // to maintain the casing consistency between "azureprofile.json" and token cache. (RD 1996587)
  51. // use the "userId" here, which should be the same with "username" except the casing.
  52. return (username.toLowerCase() === userIdFromToken.toLowerCase());
  53. }
  54. /**
  55. * Tries to get the token from cache initially. If that is unsuccessful then it tries to get the token from ADAL.
  56. * @returns {Promise<TokenResponse>}
  57. * {object} [tokenResponse] The tokenResponse (tokenType and accessToken are the two important properties).
  58. * @memberof UserTokenCredentials
  59. */
  60. public async getToken(): Promise<TokenResponse> {
  61. try {
  62. return await this.getTokenFromCache(this.username);
  63. } catch (error) {
  64. const self = this;
  65. const resource = this.getActiveDirectoryResourceId();
  66. return new Promise<TokenResponse>((resolve, reject) => {
  67. self.authContext.acquireTokenWithUsernamePassword(resource, self.username, self.password, self.clientId,
  68. (error: Error, tokenResponse: TokenResponse | ErrorResponse) => {
  69. if (error) {
  70. return reject(error);
  71. }
  72. if (tokenResponse.error || tokenResponse.errorDescription) {
  73. return reject(tokenResponse);
  74. }
  75. tokenResponse = tokenResponse as TokenResponse;
  76. if (self.crossCheckUserNameWithToken(self.username, tokenResponse.userId!)) {
  77. return resolve((tokenResponse as TokenResponse));
  78. } else {
  79. return reject(`The userId "${tokenResponse.userId}" in access token doesn"t match the username "${self.username}" provided during authentication.`);
  80. }
  81. });
  82. });
  83. }
  84. }
  85. }