deviceTokenCredentials.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 { AuthConstants, TokenAudience } from "../util/authConstants";
  6. import { TokenResponse, TokenCache } from "adal-node";
  7. export class DeviceTokenCredentials extends TokenCredentialsBase {
  8. readonly username: string;
  9. /**
  10. * Creates a new DeviceTokenCredentials object that gets a new access token using userCodeInfo (contains user_code, device_code)
  11. * for authenticating user on device.
  12. *
  13. * When this credential is used, the script will provide a url and code. The user needs to copy the url and the code, paste it
  14. * in a browser and authenticate over there. If successful, the script will get the access token.
  15. *
  16. * @constructor
  17. * @param {string} [clientId] The active directory application client id.
  18. * @param {string} [domain] The domain or tenant id containing this application. Default value is "common"
  19. * @param {string} [username] The user name for account in the form: "user@example.com".
  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. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
  23. * for an example.
  24. * @param {Environment} [environment] The azure environment to authenticate with. Default environment is "Azure" popularly known as "Public Azure Cloud".
  25. * @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal.
  26. */
  27. public constructor(
  28. clientId?: string,
  29. domain?: string,
  30. username?: string,
  31. tokenAudience?: TokenAudience,
  32. environment?: Environment,
  33. tokenCache?: TokenCache) {
  34. if (!username) {
  35. username = "user@example.com";
  36. }
  37. if (!domain) {
  38. domain = AuthConstants.AAD_COMMON_TENANT;
  39. }
  40. if (!clientId) {
  41. clientId = AuthConstants.DEFAULT_ADAL_CLIENT_ID;
  42. }
  43. super(clientId, domain, tokenAudience, environment, tokenCache);
  44. this.username = username;
  45. }
  46. public getToken(): Promise<TokenResponse> {
  47. // For device auth, this is just getTokenFromCache.
  48. return this.getTokenFromCache(this.username);
  49. }
  50. }