This commit is contained in:
Amar Zavery 2017-09-17 11:52:21 -07:00
Родитель a037205062
Коммит a1a78c2ec0
35 изменённых файлов: 1781 добавлений и 502 удалений

Просмотреть файл

@ -4,4 +4,5 @@ samples/
test/
.travis.yml
gulpfile.js
.gitignore
.gitignore
.gitattributes

5
.travis.yml Normal file
Просмотреть файл

@ -0,0 +1,5 @@
language: node_js
sudo: false
node_js:
- "6"
- "8"

8
Changelog.md Normal file
Просмотреть файл

@ -0,0 +1,8 @@
### 0.1.0 - 2017/09/16
- Initial version of ms-rest-nodeauth
- Provides following flavors of authentication in different Azure Clouds
- Authentication via service principal
- Authentication via username/password
- Interactive authentication (device code flow)
- Authentication via auth file
- MSI (Managed Service Identity) based authentication from a virtual machine created in Azure.

Просмотреть файл

@ -1,6 +1,5 @@
### Purpose
This package provides a mechanism to access the Azure Endpoints in different Azure clouds. It also provides a mechanism to add a custom environment.
This library provides different node.js based authentication mechanisms for services in Azure. It also contains rich type definitions thereby providing good typescrit experience.
All the authentication methods support callback as well as promise. IF they are called within an async method in your application then you can use the async/await pattern as well.
### Example
@ -48,7 +47,7 @@ msRestNodeAuth.interactiveLoginWithAuthResponse().then((authres) => {
```typescript
import * as msRestNodeAuth from "../lib/msRestNodeAuth";
var options: msRestNodeAuth.OptionalAuthFileParameters = {
const options: msRestNodeAuth.LoginWithAuthFileOptions = {
filePath: "<file path to auth file>",
}
msRestNodeAuth.loginWithAuthFileWithAuthResponse(options).then((authRes) => {
@ -59,6 +58,17 @@ msRestNodeAuth.loginWithAuthFileWithAuthResponse(options).then((authRes) => {
});
```
### MSI(Managed Service Identity) based login from a virtual machine created in Azure.
```typescript
import * as msRestNodeAuth from "../lib/msRestNodeAuth";
msRestNodeAuth.loginWithMSI("your-tenantId").then((msiTokenRes) => {
console.log(msiTokenRes);
}).catch((err) => {
console.log(err);
});
```
### Contributing
This project welcomes contributions and suggestions. Most contributions require you to agree to a

Просмотреть файл

@ -13,22 +13,22 @@ class ApplicationTokenCredentials extends tokenCredentialsBase_1.TokenCredential
* @param {string} clientId The active directory application client id.
* @param {string} domain The domain or tenant id containing this application.
* @param {string} secret The authentication secret for the application.
* @param {string} [tokenAudience] The audience for which the token is requested. Valid value is 'graph'. If tokenAudience is provided
* then domain should also be provided its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).
* @param {string} [tokenAudience] The audience for which the token is requested. Valid value is "graph". If tokenAudience is provided
* then domain should also be provided its value should not be the default "common" tenant. It must be a string (preferrably in a guid format).
* @param {AzureEnvironment} [environment] The azure environment to authenticate with.
* @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal.
*/
constructor(clientId, domain, secret, tokenAudience, environment, tokenCache) {
if (!Boolean(secret) || typeof secret.valueOf() !== 'string') {
throw new Error('secret must be a non empty string.');
if (!Boolean(secret) || typeof secret.valueOf() !== "string") {
throw new Error("secret must be a non empty string.");
}
super(clientId, domain, tokenAudience, environment, tokenCache);
this.secret = secret;
}
/**
* Tries to get the token from cache initially. If that is unsuccessfull then it tries to get the token from ADAL.
* @returns {Promise<TokenResponse>} A promise that resolves to TokenResponse and rejects with an Error.
*/
* Tries to get the token from cache initially. If that is unsuccessfull then it tries to get the token from ADAL.
* @returns {Promise<TokenResponse>} A promise that resolves to TokenResponse and rejects with an Error.
*/
getToken() {
return this.getTokenFromCache()
.then((tokenResponse) => tokenResponse)
@ -60,7 +60,7 @@ class ApplicationTokenCredentials extends tokenCredentialsBase_1.TokenCredential
if (status.result) {
return Promise.reject(error);
}
let msg = status && status.details && status.details.message ? status.details.message : status.details;
const msg = status && status.details && status.details.message ? status.details.message : status.details;
return Promise.reject(new Error(authConstants_1.AuthConstants.SDK_INTERNAL_ERROR + " : "
+ "critical failure while removing expired token for service principal from token cache. "
+ msg));
@ -83,7 +83,7 @@ class ApplicationTokenCredentials extends tokenCredentialsBase_1.TokenCredential
return resolve({ result: false, details: error });
}
if (entries && entries.length > 0) {
//return resolve(self.tokenCache.remove(entries, () => resolve({ result: true })));
// return resolve(self.tokenCache.remove(entries, () => resolve({ result: true })));
return new Promise((resolve) => {
return self.tokenCache.remove(entries, (err) => {
if (err) {

Просмотреть файл

@ -1 +1 @@
{"version":3,"file":"applicationTokenCredentials.js","sourceRoot":"","sources":["../../../lib/credentials/applicationTokenCredentials.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,+FAA+F;;AAE/F,iEAA6E;AAE7E,yDAAqE;AAErE,iCAAyC,SAAQ,2CAAoB;IAGnE;;;;;;;;;;;;OAYG;IACH,YACE,QAAgB,EAChB,MAAc,EACd,MAAc,EACd,aAA6B,EAC7B,WAA8B,EAC9B,UAAgB;QAEhB,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,OAAO,MAAM,CAAC,OAAO,EAAE,KAAK,QAAQ,CAAC,CAAC,CAAC;YAC7D,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;QACxD,CAAC;QACD,KAAK,CAAC,QAAQ,EAAE,MAAM,EAAE,aAAa,EAAE,WAAkB,EAAE,UAAU,CAAC,CAAC;QAEvE,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAED;;;MAGE;IACK,QAAQ;QACb,MAAM,CAAC,IAAI,CAAC,iBAAiB,EAAE;aAC5B,IAAI,CAAC,CAAC,aAAa,KAAK,aAAa,CAAC;aACtC,KAAK,CAAC,CAAC,KAAK;YACX,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,6BAAa,CAAC,kBAAkB,CAAC,CAAC,CAAC,CAAC;gBAC/D,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YAC/B,CAAC;YAED,MAAM,QAAQ,GAAG,IAAI,CAAC,4BAA4B,EAAE,CAAC;YACrD,MAAM,CAAC,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM;gBACjC,IAAI,CAAC,WAAW,CAAC,iCAAiC,CAAC,QAAQ,EAAE,IAAI,CAAC,QAAQ,EA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;IACK,2BAA2B,CAAC,KAAa;QAC/C,MAAM,IAAI,GAAG,IAAI,CAAC;QAClB,MAAM,CAAC,IAAI,OAAO,CAAuC,CAAC,OAAO;YAC/D,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,KAAY,EAAE,OAAc;gBACvD,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACV,MAAM,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;gBACpD,CAAC;gBAED,EAAE,CAAC,CAAC,OAAO,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;oBAClC,mFAAmF;oBACnF,MAAM,CAAC,IAAI,OAAO,CAAC,CAAC,OAAO;wBACzB,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,GAAU;4BAChD,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;gCACR,MAAM,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,CAAC;4BAClD,CAAC;4BACD,MAAM,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;wBACnC,CAAC,CAAC,CAAC;oBACL,CAAC,CAAC,CAAC;gBACL,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACN,MAAM,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;gBACnC,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA/GD,kEA+GC"}
{"version":3,"file":"applicationTokenCredentials.js","sourceRoot":"","sources":["../../../lib/credentials/applicationTokenCredentials.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,+FAA+F;;AAE/F,iEAA6E;AAE7E,yDAAqE;AAErE,iCAAyC,SAAQ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AO,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;gBACpD,CAAC;gBAED,EAAE,CAAC,CAAC,OAAO,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;oBAClC,oFAAoF;oBACpF,MAAM,CAAC,IAAI,OAAO,CAAC,CAAC,OAAO;wBACzB,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,GAAU;4BAChD,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;gCACR,MAAM,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,CAAC;4BAClD,CAAC;4BACD,MAAM,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;wBACnC,CAAC,CAAC,CAAC;oBACL,CAAC,CAAC,CAAC;gBACL,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACN,MAAM,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;gBACnC,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA/GD,kEA+GC"}

Просмотреть файл

@ -14,10 +14,10 @@ class DeviceTokenCredentials extends tokenCredentialsBase_1.TokenCredentialsBase
*
* @constructor
* @param {string} [clientId] The active directory application client id.
* @param {string} [domain] The domain or tenant id containing this application. Default value is 'common'
* @param {string} [username] The user name for account in the form: 'user@example.com'.
* @param {string} [tokenAudience] The audience for which the token is requested. Valid value is 'graph'. If tokenAudience is provided
* 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).
* @param {string} [domain] The domain or tenant id containing this application. Default value is "common"
* @param {string} [username] The user name for account in the form: "user@example.com".
* @param {string} [tokenAudience] The audience for which the token is requested. Valid value is "graph". If tokenAudience is provided
* 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).
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* for an example.
* @param {AzureEnvironment} [environment] The azure environment to authenticate with. Default environment is "Azure" popularly known as "Public Azure Cloud".

36
dist/lib/credentials/msiTokenCredentials.js поставляемый
Просмотреть файл

@ -10,7 +10,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const msRest = require("ms-rest-ts");
const msRest = require("ms-rest-js");
/**
* @class MSITokenCredentials - Provides information about managed service identity token credentials.
* This object can only be used to acquire token on a virtual machine provisioned in Azure with managed service identity.
@ -40,17 +40,17 @@ class MSITokenCredentials {
this.port = port;
this.resource = resource;
this.aadEndpoint = aadEndpoint;
if (!Boolean(domain) || typeof domain.valueOf() !== 'string') {
throw new TypeError('domain must be a non empty string.');
if (!Boolean(domain) || typeof domain.valueOf() !== "string") {
throw new TypeError("domain must be a non empty string.");
}
if (typeof port.valueOf() !== 'number') {
throw new Error('port must be a number.');
if (typeof port.valueOf() !== "number") {
throw new Error("port must be a number.");
}
if (typeof resource.valueOf() !== 'string') {
throw new Error('resource must be a uri of type string.');
if (typeof resource.valueOf() !== "string") {
throw new Error("resource must be a uri of type string.");
}
if (typeof aadEndpoint.valueOf() !== 'string') {
throw new Error('aadEndpoint must be a uri of type string.');
if (typeof aadEndpoint.valueOf() !== "string") {
throw new Error("aadEndpoint must be a uri of type string.");
}
}
/**
@ -63,7 +63,7 @@ class MSITokenCredentials {
getToken() {
return __awaiter(this, void 0, void 0, function* () {
const reqOptions = this.prepareRequestOptions();
let client = new msRest.ServiceClient();
const client = new msRest.ServiceClient();
let opRes;
let result;
try {
@ -85,8 +85,8 @@ class MSITokenCredentials {
prepareRequestOptions() {
const resource = encodeURIComponent(this.resource);
const aadEndpoint = encodeURIComponent(this.aadEndpoint);
const forwardSlash = encodeURIComponent('/');
let reqOptions = {
const forwardSlash = encodeURIComponent("/");
const reqOptions = {
url: `http://localhost:${this.port}/oauth2/token`,
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
@ -98,12 +98,12 @@ class MSITokenCredentials {
return reqOptions;
}
/**
* Signs a request with the Authentication header.
*
* @param {webResource} The WebResource to be signed.
* @param {function(error)} callback The callback function.
* @return {undefined}
*/
* Signs a request with the Authentication header.
*
* @param {webResource} The WebResource to be signed.
* @param {function(error)} callback The callback function.
* @return {undefined}
*/
signRequest(webResource) {
return __awaiter(this, void 0, void 0, function* () {
const tokenResponse = yield this.getToken();

Просмотреть файл

@ -1 +1 @@
{"version":3,"file":"msiTokenCredentials.js","sourceRoot":"","sources":["../../../lib/credentials/msiTokenCredentials.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,+FAA+F;;;;;;;;;;AAE/F,qCAAqC;AAQrC;;;GAGG;AACH;IACE;QACE;;WAEG;QACI,MAAc;QACrB;;WAEG;QACI,OAAe,KAAK;QAC3B;;;;;WAKG;QACI,WAAmB,8BAA8B;QACxD;;WAEG;QACI,cAAc,mCAAmC;QAfjD,WAAM,GAAN,MAAM,CAAQ;QAId,SAAI,GAAJ,IAAI,CAAgB;QAOpB,aAAQ,GAAR,QAAQ,CAAyC;QAIjD,gBAAW,GAAX,WAAW,CAAsC;QACxD,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,OAAO,MAAM,CAAC,OAAO,EAAE,KAAK,QAAQ,CAAC,CAAC,CAAC;YAC7D,MAAM,IAAI,SAAS,CAAC,oCAAoC,CAAC,CAAC;QAC5D,CAAC;QACD,EAAE,CAAC,CAAC,OAAO,IAAI,CAAC,OAAO,EAAE,KAAK,QAAQ,CAAC,CAAC,CAAC;YACvC,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;QAC5C,CAAC;QACD,EAAE,CAAC,CAAC,OAAO,QAAQ,CAAC,OAAO,EAAE,KAAK,QAAQ,CAAC,CAAC,CA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,CAAC;YAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;gBACb,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YAC7B,CAAC;YACD,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACjC,CAAC;KAAA;IAEO,qBAAqB;QAC3B,MAAM,QAAQ,GAAG,kBAAkB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACnD,MAAM,WAAW,GAAG,kBAAkB,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACzD,MAAM,YAAY,GAAG,kBAAkB,CAAC,GAAG,CAAC,CAAC;QAC7C,MAAM,UAAU,GAAiC;YAC/C,GAAG,EAAE,oBAAoB,IAAI,CAAC,IAAI,eAAe;YACjD,OAAO,EAAE;gBACP,cAAc,EAAE,kDAAkD;gBAClE,UAAU,EAAE,MAAM;aACnB;YACD,IAAI,EAAE,aAAa,WAAW,GAAG,YAAY,GAAG,IAAI,CAAC,MAAM,aAAa,QAAQ,EAAE;YAClF,MAAM,EAAE,MAAM;SACf,CAAC;QAEF,MAAM,CAAC,UAAU,CAAC;IACpB,CAAC;IAED;;;;;;OAMG;IACU,WAAW,CAAC,WAA+B;;YACtD,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,QAAQ,EAAE,CAAC;YAC5C,WAAW,CAAC,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC,eAAe,CAAC,aAAa,CAAC,GAAG,GAAG,aAAa,CAAC,SAAS,IAAI,aAAa,CAAC,WAAW,EAAE,CAAC;YAChI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;QACtC,CAAC;KAAA;CACF;AA1FD,kDA0FC"}

19
dist/lib/credentials/tokenCredentialsBase.js поставляемый
Просмотреть файл

@ -10,7 +10,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const ms_rest_ts_1 = require("ms-rest-ts");
const ms_rest_js_1 = require("ms-rest-js");
const ms_rest_azure_env_1 = require("ms-rest-azure-env");
const authConstants_1 = require("../util/authConstants");
const adal = require("adal-node");
@ -21,11 +21,11 @@ class TokenCredentialsBase {
this.tokenAudience = tokenAudience;
this.environment = environment;
this.tokenCache = tokenCache;
if (!Boolean(clientId) || typeof clientId.valueOf() !== 'string') {
throw new Error('clientId must be a non empty string.');
if (!Boolean(clientId) || typeof clientId.valueOf() !== "string") {
throw new Error("clientId must be a non empty string.");
}
if (!Boolean(domain) || typeof domain.valueOf() !== 'string') {
throw new Error('domain must be a non empty string.');
if (!Boolean(domain) || typeof domain.valueOf() !== "string") {
throw new Error("domain must be a non empty string.");
}
if (this.tokenAudience === authConstants_1.TokenAudience.graph) {
this.isGraphContext = true;
@ -55,10 +55,17 @@ class TokenCredentialsBase {
});
});
}
/**
* Signs a request with the Authentication header.
*
* @param {webResource} The WebResource to be signed.
* @param {function(error)} callback The callback function.
* @return {undefined}
*/
signRequest(webResource) {
return __awaiter(this, void 0, void 0, function* () {
const tokenResponse = yield this.getToken();
webResource.headers[ms_rest_ts_1.Constants.HeaderConstants.AUTHORIZATION] = `${tokenResponse.tokenType} ${tokenResponse.accessToken}`;
webResource.headers[ms_rest_js_1.Constants.HeaderConstants.AUTHORIZATION] = `${tokenResponse.tokenType} ${tokenResponse.accessToken}`;
return Promise.resolve(webResource);
});
}

Просмотреть файл

@ -1 +1 @@
{"version":3,"file":"tokenCredentialsBase.js","sourceRoot":"","sources":["../../../lib/credentials/tokenCredentialsBase.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,+FAA+F;;;;;;;;;;AAE/F,2CAAuE;AACvE,yDAAqD;AACrD,yDAAsD;AACtD,MAAM,IAAI,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;AAQlC;IAIE,YACkB,QAAgB,EACzB,MAAc,EACL,aAA6B,EAC7B,cAAc,oCAAgB,CAAC,KAAK,EAC7C,aAAkB,IAA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CAAC,WAAW,CAAC,yBAAyB,CAAC;QAE/C,MAAM,CAAC,QAAQ,CAAC;IAClB,CAAC;IAES,iBAAiB,CAAC,QAAiB;QAC3C,MAAM,IAAI,GAAG,IAAI,CAAC;QAClB,MAAM,QAAQ,GAAG,IAAI,CAAC,4BAA4B,EAAE,CAAC;QAErD,MAAM,CAAC,IAAI,OAAO,CAAgB,CAAC,OAAO,EAAE,MAAM;YAChD,IAAI,CAAC,WAAW,CAAC,YAAY,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,CAAC,KAAY,EAAE,aAA4B;gBAC1G,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;oBACV,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;gBACvB,CAAC;gBACD,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;YAChC,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;IAUD;;;;;;OAMG;IACU,WAAW,CAAC,WAAwB;;YAC/C,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,QAAQ,EAAE,CAAC;YAC5C,WAAW,CAAC,OAAO,CAAC,sBAAe,CAAC,eAAe,CAAC,aAAa,CAAC,GAAG,GAAG,aAAa,CAAC,SAAS,IAAI,aAAa,CAAC,WAAW,EAAE,CAAC;YAC/H,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;QACtC,CAAC;KAAA;CACF;AA1ED,oDA0EC"}

26
dist/lib/credentials/userTokenCredentials.js поставляемый
Просмотреть файл

@ -22,31 +22,31 @@ class UserTokenCredentials extends tokenCredentialsBase_1.TokenCredentialsBase {
* @param {string} domain The domain or tenant id containing this application.
* @param {string} username The user name for the Organization Id account.
* @param {string} password The password for the Organization Id account.
* @param {string} [tokenAudience] The audience for which the token is requested. Valid value is 'graph'. If tokenAudience is provided
* then domain should also be provided its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).
* @param {string} [tokenAudience] The audience for which the token is requested. Valid value is "graph". If tokenAudience is provided
* then domain should also be provided its value should not be the default "common" tenant. It must be a string (preferrably in a guid format).
* @param {AzureEnvironment} [environment] The azure environment to authenticate with.
* @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal.
*/
constructor(clientId, domain, username, password, tokenAudience, environment, tokenCache) {
if (!Boolean(clientId) || typeof clientId.valueOf() !== 'string') {
throw new Error('clientId must be a non empty string.');
if (!Boolean(clientId) || typeof clientId.valueOf() !== "string") {
throw new Error("clientId must be a non empty string.");
}
if (!Boolean(domain) || typeof domain.valueOf() !== 'string') {
throw new Error('domain must be a non empty string.');
if (!Boolean(domain) || typeof domain.valueOf() !== "string") {
throw new Error("domain must be a non empty string.");
}
if (!Boolean(username) || typeof username.valueOf() !== 'string') {
throw new Error('username must be a non empty string.');
if (!Boolean(username) || typeof username.valueOf() !== "string") {
throw new Error("username must be a non empty string.");
}
if (!Boolean(password) || typeof password.valueOf() !== 'string') {
throw new Error('password must be a non empty string.');
if (!Boolean(password) || typeof password.valueOf() !== "string") {
throw new Error("password must be a non empty string.");
}
super(clientId, domain, tokenAudience, environment, tokenCache);
this.username = username;
this.password = password;
}
crossCheckUserNameWithToken(username, userIdFromToken) {
//to maintain the casing consistency between 'azureprofile.json' and token cache. (RD 1996587)
//use the 'userId' here, which should be the same with "username" except the casing.
// to maintain the casing consistency between "azureprofile.json" and token cache. (RD 1996587)
// use the "userId" here, which should be the same with "username" except the casing.
return (username.toLowerCase() === userIdFromToken.toLowerCase());
}
/**
@ -72,7 +72,7 @@ class UserTokenCredentials extends tokenCredentialsBase_1.TokenCredentialsBase {
resolve(tokenResponse);
}
else {
reject(`The userId "${tokenResponse.userId}" in access token doesn't match the username "${self.username}" provided during authentication.`);
reject(`The userId "${tokenResponse.userId}" in access token doesn"t match the username "${self.username}" provided during authentication.`);
}
});
});

Просмотреть файл

@ -1 +1 @@
{"version":3,"file":"userTokenCredentials.js","sourceRoot":"","sources":["../../../lib/credent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C,WAAW,EAAE,KAAK,eAAe,CAAC,WAAW,EAAE,CAAC,CAAC;IACpE,CAAC;IAED;;;;;OAKG;IACU,QAAQ;;YACnB,IAAI,CAAC;gBACH,MAAM,CAAC,MAAM,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YACrD,CAAC;YAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;gBACf,MAAM,IAAI,GAAG,IAAI,CAAC;gBAClB,MAAM,QAAQ,GAAG,IAAI,CAAC,4BAA4B,EAAE,CAAC;gBAErD,MAAM,CAAC,IAAI,OAAO,CAAgB,CAAC,OAAO,EAAE,MAAM;oBAChD,IAAI,CAAC,WAAW,CAAC,gCAAgC,CAAC,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,QAAQ,EACrG,CAAC,KAAY,EAAE,aAA4B;wBACzC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;4BACV,MAAM,CAAC,KAAK,CAAC,CAAC;wBAChB,CAAC;wBACD,EAAE,CAAC,CAAC,IAAI,CAAC,2BAA2B,CAAC,IAAI,CAAC,QAAQ,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;4BAC1E,OAAO,CAAE,aAA+B,CAAC,CAAC;wBAC5C,CAAC;wBAAC,IAAI,CAAC,CAAC;4BACN,MAAM,CAAC,eAAe,aAAa,CAAC,MAAM,iDAAiD,IAAI,CAAC,QAAQ,mCAAmC,CAAC,CAAC;wBAC/I,CAAC;oBACH,CAAC,CAAC,CAAC;gBACP,CAAC,CAAC,CAAC;YACL,CAAC;QACH,CAAC;KAAA;CACF;AArFD,oDAqFC"}

127
dist/lib/login.js поставляемый
Просмотреть файл

@ -12,7 +12,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
Object.defineProperty(exports, "__esModule", { value: true });
const adal = require("adal-node");
const fs = require("fs");
const msRest = require("ms-rest-ts");
const msRest = require("ms-rest-js");
const ms_rest_azure_env_1 = require("ms-rest-azure-env");
const applicationTokenCredentials_1 = require("./credentials/applicationTokenCredentials");
const deviceTokenCredentials_1 = require("./credentials/deviceTokenCredentials");
@ -21,7 +21,7 @@ const authConstants_1 = require("./util/authConstants");
const subscriptionUtils_1 = require("./subscriptionManagement/subscriptionUtils");
const msiTokenCredentials_1 = require("./credentials/msiTokenCredentials");
function turnOnLogging() {
let log = adal.Logging;
const log = adal.Logging;
log.setLoggingOptions({
level: log.LOGGING_LEVEL.VERBOSE,
log: function (level, message, error) {
@ -33,7 +33,7 @@ function turnOnLogging() {
}
});
}
if (process.env['AZURE_ADAL_LOGGING_ENABLED']) {
if (process.env["AZURE_ADAL_LOGGING_ENABLED"]) {
turnOnLogging();
}
/**
@ -46,9 +46,9 @@ if (process.env['AZURE_ADAL_LOGGING_ENABLED']) {
* @param {string} [options.clientId] The active directory application client id.
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* for an example.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is 'graph'. If tokenAudience is provided
* 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).
* @param {string} [options.domain] The domain or tenant id containing this application. Default value 'common'.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is "graph". If tokenAudience is provided
* 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).
* @param {string} [options.domain] The domain or tenant id containing this application. Default value "common".
* @param {AzureEnvironment} [options.environment] The azure environment to authenticate with.
* @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal.
*
@ -95,7 +95,7 @@ exports.withUsernamePasswordWithAuthResponse = withUsernamePasswordWithAuthRespo
* @param {string} secret The application secret for the service principal.
* @param {string} domain The domain or tenant id containing this application.
* @param {object} [options] Object representing optional parameters.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is 'graph'.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is "graph".
* @param {AzureEnvironment} [options.environment] The azure environment to authenticate with.
* @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal.
*
@ -126,10 +126,10 @@ function withServicePrincipalSecretWithAuthResponse(clientId, secret, domain, op
exports.withServicePrincipalSecretWithAuthResponse = withServicePrincipalSecretWithAuthResponse;
function validateAuthFileContent(credsObj, filePath) {
if (!credsObj) {
throw new Error('Please provide a credsObj to validate.');
throw new Error("Please provide a credsObj to validate.");
}
if (!filePath) {
throw new Error('Please provide a filePath.');
throw new Error("Please provide a filePath.");
}
if (!credsObj.clientId) {
throw new Error(`"clientId" is missing from the auth file: ${filePath}.`);
@ -157,14 +157,14 @@ function validateAuthFileContent(credsObj, filePath) {
}
}
function foundManagementEndpointUrl(authFileUrl, envUrl) {
if (!authFileUrl || (authFileUrl && typeof authFileUrl.valueOf() !== 'string')) {
throw new Error('authFileUrl cannot be null or undefined and must be of type string.');
if (!authFileUrl || (authFileUrl && typeof authFileUrl.valueOf() !== "string")) {
throw new Error("authFileUrl cannot be null or undefined and must be of type string.");
}
if (!envUrl || (envUrl && typeof envUrl.valueOf() !== 'string')) {
throw new Error('envUrl cannot be null or undefined and must be of type string.');
if (!envUrl || (envUrl && typeof envUrl.valueOf() !== "string")) {
throw new Error("envUrl cannot be null or undefined and must be of type string.");
}
authFileUrl = authFileUrl.endsWith('/') ? authFileUrl.slice(0, -1) : authFileUrl;
envUrl = envUrl.endsWith('/') ? envUrl.slice(0, -1) : envUrl;
authFileUrl = authFileUrl.endsWith("/") ? authFileUrl.slice(0, -1) : authFileUrl;
envUrl = envUrl.endsWith("/") ? envUrl.slice(0, -1) : envUrl;
return (authFileUrl.toLowerCase() === envUrl.toLowerCase());
}
/**
@ -180,13 +180,13 @@ function foundManagementEndpointUrl(authFileUrl, envUrl) {
*
* Authenticates using the service principal information provided in the auth file. This method will set
* the subscriptionId from the auth file to the user provided environment variable in the options
* parameter or the default 'AZURE_SUBSCRIPTION_ID'.
* parameter or the default "AZURE_SUBSCRIPTION_ID".
*
* @param {object} [options] - Optional parameters
* @param {string} [options.filePath] - Absolute file path to the auth file. If not provided
* then please set the environment variable AZURE_AUTH_LOCATION.
* @param {string} [options.subscriptionEnvVariableName] - The subscriptionId environment variable
* name. Default is 'AZURE_SUBSCRIPTION_ID'.
* name. Default is "AZURE_SUBSCRIPTION_ID".
* @param {function} [optionalCallback] The optional callback.
*
* @returns {Promise<AuthResponse>} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error.
@ -194,16 +194,17 @@ function foundManagementEndpointUrl(authFileUrl, envUrl) {
function withAuthFileWithAuthResponse(options) {
return __awaiter(this, void 0, void 0, function* () {
if (!options)
options = { filePath: '' };
let filePath = options.filePath || process.env[authConstants_1.AuthConstants.AZURE_AUTH_LOCATION];
let subscriptionEnvVariableName = options.subscriptionEnvVariableName || 'AZURE_SUBSCRIPTION_ID';
options = { filePath: "" };
const filePath = options.filePath || process.env[authConstants_1.AuthConstants.AZURE_AUTH_LOCATION];
const subscriptionEnvVariableName = options.subscriptionEnvVariableName || "AZURE_SUBSCRIPTION_ID";
if (!filePath) {
let msg = `Either provide an absolute file path to the auth file or set/export the environment variable - ${authConstants_1.AuthConstants.AZURE_AUTH_LOCATION}.`;
const msg = `Either provide an absolute file path to the auth file or set/export the environment variable - ${authConstants_1.AuthConstants.AZURE_AUTH_LOCATION}.`;
return Promise.reject(new Error(msg));
}
let content, credsObj = {}, optionsForSpSecret = {};
let content, credsObj = {};
const optionsForSpSecret = {};
try {
content = fs.readFileSync(filePath, { encoding: 'utf8' });
content = fs.readFileSync(filePath, { encoding: "utf8" });
credsObj = JSON.parse(content);
validateAuthFileContent(credsObj, filePath);
}
@ -213,16 +214,16 @@ function withAuthFileWithAuthResponse(options) {
if (!credsObj.managementEndpointUrl) {
credsObj.managementEndpointUrl = credsObj.resourceManagerEndpointUrl;
}
//setting the subscriptionId from auth file to the environment variable
// setting the subscriptionId from auth file to the environment variable
process.env[subscriptionEnvVariableName] = credsObj.subscriptionId;
//get the AzureEnvironment or create a new AzureEnvironment based on the info provided in the auth file
let envFound = {
name: ''
// get the AzureEnvironment or create a new AzureEnvironment based on the info provided in the auth file
const envFound = {
name: ""
};
let envNames = Object.keys(ms_rest_azure_env_1.AzureEnvironment);
const envNames = Object.keys(ms_rest_azure_env_1.AzureEnvironment);
for (let i = 0; i < envNames.length; i++) {
let env = envNames[i];
let environmentObj = ms_rest_azure_env_1.AzureEnvironment[env];
const env = envNames[i];
const environmentObj = ms_rest_azure_env_1.AzureEnvironment[env];
if (environmentObj &&
environmentObj.managementEndpointUrl &&
foundManagementEndpointUrl(credsObj.managementEndpointUrl, environmentObj.managementEndpointUrl)) {
@ -234,17 +235,17 @@ function withAuthFileWithAuthResponse(options) {
optionsForSpSecret.environment = ms_rest_azure_env_1.AzureEnvironment[envFound.name];
}
else {
//create a new environment with provided info.
let envParams = {
//try to find a logical name or set the filepath as the env name.
// create a new environment with provided info.
const envParams = {
// try to find a logical name or set the filepath as the env name.
name: credsObj.managementEndpointUrl.match(/.*management\.core\.(.*)\..*/i)[1] || filePath
};
let keys = Object.keys(credsObj);
const keys = Object.keys(credsObj);
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
const key = keys[i];
if (key.match(/^(clientId|clientSecret|subscriptionId|tenantId)$/ig) === null) {
if (key === 'activeDirectoryEndpointUrl' && !key.endsWith('/')) {
envParams[key] = credsObj[key] + '/';
if (key === "activeDirectoryEndpointUrl" && !key.endsWith("/")) {
envParams[key] = credsObj[key] + "/";
}
else {
envParams[key] = credsObj[key];
@ -255,7 +256,7 @@ function withAuthFileWithAuthResponse(options) {
envParams.activeDirectoryResourceId = credsObj.managementEndpointUrl;
}
if (!envParams.portalUrl) {
envParams.portalUrl = 'https://portal.azure.com';
envParams.portalUrl = "https://portal.azure.com";
}
optionsForSpSecret.environment = ms_rest_azure_env_1.AzureEnvironment.add(envParams);
}
@ -273,16 +274,16 @@ exports.withAuthFileWithAuthResponse = withAuthFileWithAuthResponse;
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* for an example.
*
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is 'graph'.If tokenAudience is provided
* then domain should also be provided its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is "graph".If tokenAudience is provided
* then domain should also be provided its value should not be the default "common" tenant. It must be a string (preferrably in a guid format).
*
* @param {string} [options.domain] The domain or tenant id containing this application. Default value is 'common'.
* @param {string} [options.domain] The domain or tenant id containing this application. Default value is "common".
*
* @param {AzureEnvironment} [options.environment] The azure environment to authenticate with. Default environment is "Public Azure".
*
* @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal.
*
* @param {object} [options.language] The language code specifying how the message should be localized to. Default value 'en-us'.
* @param {object} [options.language] The language code specifying how the message should be localized to. Default value "en-us".
*
* @param {object|function} [options.userCodeResponseLogger] A logger that logs the user code response message required for interactive login. When
* this option is specified the usercode response message will not be logged to console.
@ -314,7 +315,7 @@ function withInteractiveWithAuthResponse(options) {
if (!options.language) {
options.language = authConstants_1.AuthConstants.DEFAULT_LANGUAGE;
}
let interactiveOptions = {};
const interactiveOptions = {};
interactiveOptions.tokenAudience = options.tokenAudience;
interactiveOptions.environment = options.environment;
interactiveOptions.domain = options.domain;
@ -322,12 +323,12 @@ function withInteractiveWithAuthResponse(options) {
interactiveOptions.tokenCache = options.tokenCache;
interactiveOptions.language = options.language;
interactiveOptions.userCodeResponseLogger = options.userCodeResponseLogger;
let authorityUrl = interactiveOptions.environment.activeDirectoryEndpointUrl + interactiveOptions.domain;
let authContext = new adal.AuthenticationContext(authorityUrl, interactiveOptions.environment.validateAuthority, interactiveOptions.tokenCache);
const authorityUrl = interactiveOptions.environment.activeDirectoryEndpointUrl + interactiveOptions.domain;
const authContext = new adal.AuthenticationContext(authorityUrl, interactiveOptions.environment.validateAuthority, interactiveOptions.tokenCache);
interactiveOptions.context = authContext;
let userCodeResponse;
let creds;
let getUserCode = new Promise((resolve, reject) => {
const getUserCode = new Promise((resolve, reject) => {
return authContext.acquireUserCode(interactiveOptions.environment.activeDirectoryResourceId, interactiveOptions.clientId, interactiveOptions.language, (err, userCodeRes) => {
if (err) {
return reject(err);
@ -376,11 +377,11 @@ function withInteractiveWithAuthResponse(options) {
}
exports.withInteractiveWithAuthResponse = withInteractiveWithAuthResponse;
function withAuthFile(options, callback) {
if (!callback && typeof options === 'function') {
if (!callback && typeof options === "function") {
callback = options;
options = undefined;
}
let cb = callback;
const cb = callback;
if (!callback) {
return withAuthFileWithAuthResponse(options).then((authRes) => {
return Promise.resolve(authRes.credentials);
@ -393,17 +394,17 @@ function withAuthFile(options, callback) {
if (err) {
return cb(err);
}
return cb(null, authRes.credentials, authRes.subscriptions);
return cb(undefined, authRes.credentials, authRes.subscriptions);
});
}
}
exports.withAuthFile = withAuthFile;
function interactive(options, callback) {
if (!callback && typeof options === 'function') {
if (!callback && typeof options === "function") {
callback = options;
options = undefined;
}
let cb = callback;
const cb = callback;
if (!callback) {
return withInteractiveWithAuthResponse(options).then((authRes) => {
return Promise.resolve(authRes.credentials);
@ -416,17 +417,17 @@ function interactive(options, callback) {
if (err) {
return cb(err);
}
return cb(null, authRes.credentials, authRes.subscriptions);
return cb(undefined, authRes.credentials, authRes.subscriptions);
});
}
}
exports.interactive = interactive;
function withServicePrincipalSecret(clientId, secret, domain, options, callback) {
if (!callback && typeof options === 'function') {
if (!callback && typeof options === "function") {
callback = options;
options = undefined;
}
let cb = callback;
const cb = callback;
if (!callback) {
return withServicePrincipalSecretWithAuthResponse(clientId, secret, domain, options).then((authRes) => {
return Promise.resolve(authRes.credentials);
@ -439,17 +440,17 @@ function withServicePrincipalSecret(clientId, secret, domain, options, callback)
if (err) {
return cb(err);
}
return cb(null, authRes.credentials, authRes.subscriptions);
return cb(undefined, authRes.credentials, authRes.subscriptions);
});
}
}
exports.withServicePrincipalSecret = withServicePrincipalSecret;
function withUsernamePassword(username, password, options, callback) {
if (!callback && typeof options === 'function') {
if (!callback && typeof options === "function") {
callback = options;
options = undefined;
}
let cb = callback;
const cb = callback;
if (!callback) {
return withUsernamePasswordWithAuthResponse(username, password, options).then((authRes) => {
return Promise.resolve(authRes.credentials);
@ -462,7 +463,7 @@ function withUsernamePassword(username, password, options, callback) {
if (err) {
return cb(err);
}
return cb(null, authRes.credentials, authRes.subscriptions);
return cb(undefined, authRes.credentials, authRes.subscriptions);
});
}
}
@ -470,8 +471,8 @@ exports.withUsernamePassword = withUsernamePassword;
/**
* Initializes MSITokenCredentials class and calls getToken and returns a token response.
*
* @param {string} domain -- required. The tenant id.
* @param {object} options -- Optional parameters
* @param {string} domain - required. The tenant id.
* @param {object} options - Optional parameters
* @param {string} [options.port] - port on which the MSI service is running on the host VM. Default port is 50342
* @param {string} [options.resource] - The resource uri or token audience for which the token is needed. Default - "https://management.azure.com"
* @param {string} [options.aadEndpoint] - The add endpoint for authentication. default - "https://login.microsoftonline.com"
@ -485,11 +486,11 @@ function _withMSI(domain, options) {
return creds.getToken();
}
function withMSI(domain, options, callback) {
if (!callback && typeof options === 'function') {
if (!callback && typeof options === "function") {
callback = options;
options = {};
}
let cb = callback;
const cb = callback;
if (!callback) {
return _withMSI(domain, options);
}
@ -498,7 +499,7 @@ function withMSI(domain, options, callback) {
if (err) {
return cb(err);
}
return cb(null, tokenRes);
return cb(undefined, tokenRes);
});
}
}

2
dist/lib/login.js.map поставляемый

Различия файлов скрыты, потому что одна или несколько строк слишком длинны

Просмотреть файл

@ -10,12 +10,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const msRest = require("ms-rest-ts");
const msRest = require("ms-rest-js");
const applicationTokenCredentials_1 = require("../credentials/applicationTokenCredentials");
const authConstants_1 = require("../util/authConstants");
/**
* Builds an array of tenantIds.
* @param {TokenCredentialsBase} credentials
* @param {TokenCredentialsBase} credentials The credentials.
* @param {string} apiVersion default value 2016-06-01
* @returns {Promise<string[]>} resolves to an array of tenantIds and rejects with an error.
*/
@ -24,10 +24,10 @@ function buildTenantList(credentials, apiVersion = "2016-06-01") {
if (credentials.domain && credentials.domain !== authConstants_1.AuthConstants.AAD_COMMON_TENANT) {
return Promise.resolve([credentials.domain]);
}
let client = new msRest.ServiceClient(credentials);
let baseUrl = credentials.environment.resourceManagerEndpointUrl;
let reqUrl = `${baseUrl}${baseUrl.endsWith('/') ? '' : '/'}tenants?api-version=${apiVersion}`;
let req = {
const client = new msRest.ServiceClient(credentials);
const baseUrl = credentials.environment.resourceManagerEndpointUrl;
const reqUrl = `${baseUrl}${baseUrl.endsWith("/") ? "" : "/"}tenants?api-version=${apiVersion}`;
const req = {
url: reqUrl,
method: "GET",
};
@ -38,9 +38,9 @@ function buildTenantList(credentials, apiVersion = "2016-06-01") {
catch (err) {
return Promise.reject(err);
}
let result = [];
let tenants = res.bodyAsJson;
for (let tenant in tenants.value) {
const result = [];
const tenants = res.bodyAsJson;
for (const tenant in tenants.value) {
result.push(tenant.tenantId);
}
return Promise.resolve(result);
@ -50,22 +50,22 @@ exports.buildTenantList = buildTenantList;
function getSubscriptionsFromTenants(credentials, tenantList, apiVersion = "2016-06-01") {
return __awaiter(this, void 0, void 0, function* () {
let subscriptions = [];
let userType = 'user';
let userType = "user";
let username;
let originalDomain = credentials.domain;
const originalDomain = credentials.domain;
if (credentials instanceof applicationTokenCredentials_1.ApplicationTokenCredentials) {
userType = 'servicePrincipal';
userType = "servicePrincipal";
username = credentials.clientId;
}
else {
username = credentials.username;
}
for (let tenant of tenantList) {
for (const tenant of tenantList) {
credentials.domain = tenant;
let client = new msRest.ServiceClient(credentials);
let baseUrl = credentials.environment.resourceManagerEndpointUrl;
let reqUrl = `${baseUrl}${baseUrl.endsWith('/') ? '' : '/'}subscriptions?api-version=${apiVersion}`;
let req = {
const client = new msRest.ServiceClient(credentials);
const baseUrl = credentials.environment.resourceManagerEndpointUrl;
const reqUrl = `${baseUrl}${baseUrl.endsWith("/") ? "" : "/"}subscriptions?api-version=${apiVersion}`;
const req = {
url: reqUrl,
method: "GET",
};
@ -76,7 +76,7 @@ function getSubscriptionsFromTenants(credentials, tenantList, apiVersion = "2016
catch (err) {
return Promise.reject(err);
}
let subscriptionList = res.bodyAsJson.value;
const subscriptionList = res.bodyAsJson.value;
subscriptions = subscriptions.concat(subscriptionList.map((s) => {
s.tenantId = tenant;
s.user = { name: username, type: userType };

Просмотреть файл

@ -1 +1 @@
{"version":3,"file":"subscriptionUtils.js","sourceRoot":"","sources":["../../../lib/subscriptionManagement/subscriptionUtils.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,+FAA+F;;;;;;;;;;AAE/F,qCAAqC;AAErC,4FAAyF;AACzF,yDAAqD;AAuDrD;;;;;GAKG;AACH,yBAAsC,WAAiC,EAAE,UAAU,GAAG,YAAY;;QAChG,EAAE,CAAC,CAAC,WAAW,CAAC,MAAM,IAAI,WAAW,CAAC,MAAM,KAAK,6BAAa,CAAC,iBAAiB,CAAC,CAAC,CAAC;YACjF,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;QAC/C,CAAC;QAED,IAAI,MAAM,GAAG,IAAI,MAAM,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC;QACnD,IAAI,OAAO,GAAG,WAAW,CAAC,WAAW,CAAC,0BAA0B,CAAC;QACjE,IAAI,MAAM,GAAG,GAAG,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,GAAG,uBAAuB,UAAU,EAAE,CAAC;QAC9F,IAAI,GAAG,GAAiC;YACtC,GAAG,EAAE,MAAM;YACX,MAAM,EAAE,KAAK;SACd,CAAA;QACD,IAAI,GAAiC,CAAC;QACtC,IAAI,CAAC;YACH,GAAG,GAAG,MAAM,MAAM,CAAC,WAAW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C7B,CAAC;YAED,MAAM,gBAAgB,GAAgB,GAAG,CAAC,UAAW,CAAC,KAAK,CAAC;YAC5D,aAAa,GAAG,aAAa,CAAC,MAAM,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC,CAAM;gBAC/D,CAAC,CAAC,QAAQ,GAAG,MAAM,CAAC;gBACpB,CAAC,CAAC,IAAI,GAAG,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;gBAC5C,CAAC,CAAC,eAAe,GAAG,WAAW,CAAC,WAAW,CAAC,IAAI,CAAC;gBACjD,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,WAAW,CAAC;gBACvB,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,cAAc,CAAC;gBACxB,OAAO,CAAC,CAAC,WAAW,CAAC;gBACrB,OAAO,CAAC,CAAC,cAAc,CAAC;gBACxB,OAAO,CAAC,CAAC,oBAAoB,CAAC;gBAC9B,MAAM,CAAC,CAAC,CAAC;YACX,CAAC,CAAC,CAAC,CAAC;QACN,CAAC;QACD,6BAA6B;QAC7B,WAAW,CAAC,MAAM,GAAG,cAAc,CAAC;QACpC,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;IACxC,CAAC;CAAA;AA3CD,kEA2CC"}

Просмотреть файл

@ -10,14 +10,14 @@ export class ApplicationTokenCredentials extends TokenCredentialsBase {
private readonly secret: string;
/**
* Creates a new ApplicationTokenCredentials object.
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* for detailed instructions on creating an Azure Active Directory application.
* @constructor
* @param {string} clientId The active directory application client id.
* @param {string} clientId The active directory application client id.
* @param {string} domain The domain or tenant id containing this application.
* @param {string} secret The authentication secret for the application.
* @param {string} [tokenAudience] The audience for which the token is requested. Valid value is 'graph'. If tokenAudience is provided
* then domain should also be provided its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).
* @param {string} [tokenAudience] The audience for which the token is requested. Valid value is "graph". If tokenAudience is provided
* then domain should also be provided its value should not be the default "common" tenant. It must be a string (preferrably in a guid format).
* @param {AzureEnvironment} [environment] The azure environment to authenticate with.
* @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal.
*/
@ -29,8 +29,8 @@ export class ApplicationTokenCredentials extends TokenCredentialsBase {
environment?: AzureEnvironment,
tokenCache?: any) {
if (!Boolean(secret) || typeof secret.valueOf() !== 'string') {
throw new Error('secret must be a non empty string.');
if (!Boolean(secret) || typeof secret.valueOf() !== "string") {
throw new Error("secret must be a non empty string.");
}
super(clientId, domain, tokenAudience, environment as any, tokenCache);
@ -38,9 +38,9 @@ export class ApplicationTokenCredentials extends TokenCredentialsBase {
}
/**
* Tries to get the token from cache initially. If that is unsuccessfull then it tries to get the token from ADAL.
* @returns {Promise<TokenResponse>} A promise that resolves to TokenResponse and rejects with an Error.
*/
* Tries to get the token from cache initially. If that is unsuccessfull then it tries to get the token from ADAL.
* @returns {Promise<TokenResponse>} A promise that resolves to TokenResponse and rejects with an Error.
*/
public getToken(): Promise<TokenResponse> {
return this.getTokenFromCache()
.then((tokenResponse) => tokenResponse)
@ -76,7 +76,7 @@ export class ApplicationTokenCredentials extends TokenCredentialsBase {
if (status.result) {
return Promise.reject(error);
}
let msg = status && status.details && status.details.message ? status.details.message : status.details;
const msg = status && status.details && status.details.message ? status.details.message : status.details;
return Promise.reject(new Error(AuthConstants.SDK_INTERNAL_ERROR + " : "
+ "critical failure while removing expired token for service principal from token cache. "
+ msg));
@ -86,7 +86,7 @@ export class ApplicationTokenCredentials extends TokenCredentialsBase {
/**
* Removes invalid items from token cache. This method is different. Here we never reject in case of error.
* Rather we resolve with an object that says the result is false and error information is provided in
* Rather we resolve with an object that says the result is false and error information is provided in
* the details property of the resolved object. This is done to do better error handling in the above function
* where removeInvalidItemsFromCache() is called.
* @param {object} query The query to be used for finding the token for service principal from the cache
@ -101,7 +101,7 @@ export class ApplicationTokenCredentials extends TokenCredentialsBase {
}
if (entries && entries.length > 0) {
//return resolve(self.tokenCache.remove(entries, () => resolve({ result: true })));
// return resolve(self.tokenCache.remove(entries, () => resolve({ result: true })));
return new Promise((resolve) => {
return self.tokenCache.remove(entries, (err: Error) => {
if (err) {

Просмотреть файл

@ -13,16 +13,16 @@ export class DeviceTokenCredentials extends TokenCredentialsBase {
* Creates a new DeviceTokenCredentials object that gets a new access token using userCodeInfo (contains user_code, device_code)
* for authenticating user on device.
*
* 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
* 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
* in a browser and authenticate over there. If successful, the script will get the access token.
*
* @constructor
* @param {string} [clientId] The active directory application client id.
* @param {string} [domain] The domain or tenant id containing this application. Default value is 'common'
* @param {string} [username] The user name for account in the form: 'user@example.com'.
* @param {string} [tokenAudience] The audience for which the token is requested. Valid value is 'graph'. If tokenAudience is provided
* 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).
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* @param {string} [domain] The domain or tenant id containing this application. Default value is "common"
* @param {string} [username] The user name for account in the form: "user@example.com".
* @param {string} [tokenAudience] The audience for which the token is requested. Valid value is "graph". If tokenAudience is provided
* 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).
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* for an example.
* @param {AzureEnvironment} [environment] The azure environment to authenticate with. Default environment is "Azure" popularly known as "Public Azure Cloud".
* @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal.

Просмотреть файл

@ -1,11 +1,23 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
import * as msRest from "ms-rest-ts";
import * as msRest from "ms-rest-js";
/**
* @interface MSITokenResponse - Describes the MSITokenResponse.
*/
export interface MSITokenResponse {
/**
* @property {string} token_type - The token type.
*/
readonly token_type: string;
/**
* @property {string} access_token - The access token.
*/
readonly access_token: string;
/**
* @property {any} any - Placeholder for unknown properties.
*/
readonly [x: string]: any;
}
@ -22,29 +34,29 @@ export class MSITokenCredentials {
/**
* @property {number} port - Port on which the MSI service is running on the host VM. Default port is 50342
*/
public port: number = 50342,
public port = 50342,
/**
* @property {string} resource - The resource uri or token audience for which the token is needed.
* For e.g. it can be:
* - resourcemanagement endpoint "https://management.azure.com"(default)
* - management endpoint "https://management.core.windows.net/"
*/
public resource: string = "https://management.azure.com",
public resource = "https://management.azure.com",
/**
* @property {string} aadEndpoint - The add endpoint for authentication. default - "https://login.microsoftonline.com"
*/
public aadEndpoint = "https://login.microsoftonline.com") {
if (!Boolean(domain) || typeof domain.valueOf() !== 'string') {
throw new TypeError('domain must be a non empty string.');
if (!Boolean(domain) || typeof domain.valueOf() !== "string") {
throw new TypeError("domain must be a non empty string.");
}
if (typeof port.valueOf() !== 'number') {
throw new Error('port must be a number.');
if (typeof port.valueOf() !== "number") {
throw new Error("port must be a number.");
}
if (typeof resource.valueOf() !== 'string') {
throw new Error('resource must be a uri of type string.');
if (typeof resource.valueOf() !== "string") {
throw new Error("resource must be a uri of type string.");
}
if (typeof aadEndpoint.valueOf() !== 'string') {
throw new Error('aadEndpoint must be a uri of type string.');
if (typeof aadEndpoint.valueOf() !== "string") {
throw new Error("aadEndpoint must be a uri of type string.");
}
}
@ -53,13 +65,13 @@ export class MSITokenCredentials {
* @param {function} callback The callback in the form (err, result)
* @return {function} callback
* {Error} [err] The error if any
* {object} [tokenResponse] The tokenResponse (token_type and access_token are the two important properties).
* {object} [tokenResponse] The tokenResponse (token_type and access_token are the two important properties).
*/
async getToken(): Promise<MSITokenResponse> {
const reqOptions = this.prepareRequestOptions();
let client = new msRest.ServiceClient();
const client = new msRest.ServiceClient();
let opRes: msRest.HttpOperationResponse;
let result: MSITokenResponse
let result: MSITokenResponse;
try {
opRes = await client.sendRequest(reqOptions);
result = opRes.bodyAsJson as MSITokenResponse;
@ -74,11 +86,11 @@ export class MSITokenCredentials {
return Promise.resolve(result);
}
prepareRequestOptions(): msRest.RequestPrepareOptions {
private prepareRequestOptions(): msRest.RequestPrepareOptions {
const resource = encodeURIComponent(this.resource);
const aadEndpoint = encodeURIComponent(this.aadEndpoint);
const forwardSlash = encodeURIComponent('/');
let reqOptions: msRest.RequestPrepareOptions = {
const forwardSlash = encodeURIComponent("/");
const reqOptions: msRest.RequestPrepareOptions = {
url: `http://localhost:${this.port}/oauth2/token`,
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
@ -92,12 +104,12 @@ export class MSITokenCredentials {
}
/**
* Signs a request with the Authentication header.
*
* @param {webResource} The WebResource to be signed.
* @param {function(error)} callback The callback function.
* @return {undefined}
*/
* Signs a request with the Authentication header.
*
* @param {webResource} The WebResource to be signed.
* @param {function(error)} callback The callback function.
* @return {undefined}
*/
public async signRequest(webResource: msRest.WebResource): Promise<msRest.WebResource> {
const tokenResponse = await this.getToken();
webResource.headers[msRest.Constants.HeaderConstants.AUTHORIZATION] = `${tokenResponse.tokenType} ${tokenResponse.accessToken}`;

Просмотреть файл

@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
import { Constants as MSRestConstants, WebResource } from "ms-rest-ts";
import { Constants as MSRestConstants, WebResource } from "ms-rest-js";
import { AzureEnvironment } from "ms-rest-azure-env";
import { TokenAudience } from "../util/authConstants";
const adal = require("adal-node");
@ -23,12 +23,12 @@ export abstract class TokenCredentialsBase {
public readonly environment = AzureEnvironment.Azure,
public tokenCache: any = new adal.MemoryCache()) {
if (!Boolean(clientId) || typeof clientId.valueOf() !== 'string') {
throw new Error('clientId must be a non empty string.');
if (!Boolean(clientId) || typeof clientId.valueOf() !== "string") {
throw new Error("clientId must be a non empty string.");
}
if (!Boolean(domain) || typeof domain.valueOf() !== 'string') {
throw new Error('domain must be a non empty string.');
if (!Boolean(domain) || typeof domain.valueOf() !== "string") {
throw new Error("domain must be a non empty string.");
}
if (this.tokenAudience === TokenAudience.graph) {
@ -66,8 +66,21 @@ export abstract class TokenCredentialsBase {
});
}
/**
* Tries to get the token from cache initially. If that is unsuccessful then it tries to get the token from ADAL.
* @returns {Promise<TokenResponse>}
* {object} [tokenResponse] The tokenResponse (tokenType and accessToken are the two important properties).
* @memberof TokenCredentialsBase
*/
public async abstract getToken(): Promise<TokenResponse>;
/**
* Signs a request with the Authentication header.
*
* @param {webResource} The WebResource to be signed.
* @param {function(error)} callback The callback function.
* @return {undefined}
*/
public async signRequest(webResource: WebResource): Promise<WebResource> {
const tokenResponse = await this.getToken();
webResource.headers[MSRestConstants.HeaderConstants.AUTHORIZATION] = `${tokenResponse.tokenType} ${tokenResponse.accessToken}`;

Просмотреть файл

@ -14,14 +14,14 @@ export class UserTokenCredentials extends TokenCredentialsBase {
* Creates a new UserTokenCredentials object.
*
* @constructor
* @param {string} clientId The active directory application client id.
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* @param {string} clientId The active directory application client id.
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* for an example.
* @param {string} domain The domain or tenant id containing this application.
* @param {string} username The user name for the Organization Id account.
* @param {string} password The password for the Organization Id account.
* @param {string} [tokenAudience] The audience for which the token is requested. Valid value is 'graph'. If tokenAudience is provided
* then domain should also be provided its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).
* @param {string} [tokenAudience] The audience for which the token is requested. Valid value is "graph". If tokenAudience is provided
* then domain should also be provided its value should not be the default "common" tenant. It must be a string (preferrably in a guid format).
* @param {AzureEnvironment} [environment] The azure environment to authenticate with.
* @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal.
*/
@ -34,20 +34,20 @@ export class UserTokenCredentials extends TokenCredentialsBase {
environment?: AzureEnvironment,
tokenCache?: any) {
if (!Boolean(clientId) || typeof clientId.valueOf() !== 'string') {
throw new Error('clientId must be a non empty string.');
if (!Boolean(clientId) || typeof clientId.valueOf() !== "string") {
throw new Error("clientId must be a non empty string.");
}
if (!Boolean(domain) || typeof domain.valueOf() !== 'string') {
throw new Error('domain must be a non empty string.');
if (!Boolean(domain) || typeof domain.valueOf() !== "string") {
throw new Error("domain must be a non empty string.");
}
if (!Boolean(username) || typeof username.valueOf() !== 'string') {
throw new Error('username must be a non empty string.');
if (!Boolean(username) || typeof username.valueOf() !== "string") {
throw new Error("username must be a non empty string.");
}
if (!Boolean(password) || typeof password.valueOf() !== 'string') {
throw new Error('password must be a non empty string.');
if (!Boolean(password) || typeof password.valueOf() !== "string") {
throw new Error("password must be a non empty string.");
}
super(clientId, domain, tokenAudience, environment as any, tokenCache);
@ -57,8 +57,8 @@ export class UserTokenCredentials extends TokenCredentialsBase {
}
private crossCheckUserNameWithToken(username: string, userIdFromToken: string): boolean {
//to maintain the casing consistency between 'azureprofile.json' and token cache. (RD 1996587)
//use the 'userId' here, which should be the same with "username" except the casing.
// to maintain the casing consistency between "azureprofile.json" and token cache. (RD 1996587)
// use the "userId" here, which should be the same with "username" except the casing.
return (username.toLowerCase() === userIdFromToken.toLowerCase());
}
@ -84,7 +84,7 @@ export class UserTokenCredentials extends TokenCredentialsBase {
if (self.crossCheckUserNameWithToken(self.username, tokenResponse.userId)) {
resolve((tokenResponse as TokenResponse));
} else {
reject(`The userId "${tokenResponse.userId}" in access token doesn't match the username "${self.username}" provided during authentication.`);
reject(`The userId "${tokenResponse.userId}" in access token doesn"t match the username "${self.username}" provided during authentication.`);
}
});
});

Просмотреть файл

@ -3,18 +3,18 @@
const adal = require("adal-node");
import * as fs from "fs";
import * as msRest from "ms-rest-ts";
import * as msRest from "ms-rest-js";
import { AzureEnvironment } from "ms-rest-azure-env";
import { TokenResponse, TokenCredentialsBase } from "./credentials/tokenCredentialsBase";
import { ApplicationTokenCredentials } from "./credentials/applicationTokenCredentials";
import { DeviceTokenCredentials } from "./credentials/deviceTokenCredentials";
import { UserTokenCredentials } from "./credentials/userTokenCredentials";
import { AuthConstants, TokenAudience } from "./util/authConstants";
import { buildTenantList, getSubscriptionsFromTenants, SubscriptionInfo } from "./subscriptionManagement/subscriptionUtils";
import { buildTenantList, getSubscriptionsFromTenants, LinkedSubscription } from "./subscriptionManagement/subscriptionUtils";
import { MSITokenCredentials, MSITokenResponse } from "./credentials/msiTokenCredentials";
function turnOnLogging() {
let log = adal.Logging;
const log = adal.Logging;
log.setLoggingOptions(
{
level: log.LOGGING_LEVEL.VERBOSE,
@ -28,37 +28,57 @@ function turnOnLogging() {
});
}
if (process.env['AZURE_ADAL_LOGGING_ENABLED']) {
if (process.env["AZURE_ADAL_LOGGING_ENABLED"]) {
turnOnLogging();
}
/**
* @interface OptionalInteractiveParameters - Describes optional parameters for serviceprincipal/secret authentication.
* @interface AzureTokenCredentialsOptions - Describes optional parameters for serviceprincipal/secret authentication.
*/
export interface OptionalServicePrincipalParameters {
export interface AzureTokenCredentialsOptions {
/**
* @property {TokenAudience} [tokenAudience] - The audience for which the token is requested. Valid value is "graph". If tokenAudience is provided
* 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).
*/
tokenAudience?: TokenAudience;
/**
* @property {AzureEnvironment} [environment] - The Azure environment to authenticate with.
*/
environment?: AzureEnvironment;
/**
* @property {any} [tokenCache] - The token cache. Default value is MemoryCache from adal.
*/
tokenCache?: any;
}
/**
* @interface OptionalInteractiveParameters - Describes optional parameters for username/password authentication.
* @interface LoginWithUsernamePasswordOptions - Describes optional parameters for username/password authentication.
*/
export interface OptionalUsernamePasswordParameters extends OptionalServicePrincipalParameters {
export interface LoginWithUsernamePasswordOptions extends AzureTokenCredentialsOptions {
/**
* @property {string} [clientId] - The active directory application client id.
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* for an example.
*/
clientId?: string;
/**
* @property {string} [domain] - The domain or tenant id containing this application. Default value is "common".
*/
domain?: string;
}
/**
* @interface OptionalInteractiveParameters - Describes optional parameters for interactive authentication.
* @interface InteractiveLoginOptions - Describes optional parameters for interactive authentication.
*/
export interface OptionalInteractiveParameters extends OptionalUsernamePasswordParameters {
export interface InteractiveLoginOptions extends LoginWithUsernamePasswordOptions {
/**
* @property {object|function} [userCodeResponseLogger] A logger that logs the user code response message required for interactive login. When
* this option is specified the usercode response message will not be logged to console.
*/
userCodeResponseLogger?: any
userCodeResponseLogger?: any;
/**
* @property {string} [language] The language code specifying how the message should be localized to. Default value 'en-us'.
* @property {string} [language] The language code specifying how the message should be localized to. Default value "en-us".
*/
language?: string;
}
@ -72,15 +92,15 @@ export interface AuthResponse {
*/
credentials: TokenCredentialsBase;
/**
* @property {Array<SubscriptionInfo>} [subscriptions] List of associated subscriptions.
* @property {Array<LinkedSubscription>} [subscriptions] List of associated subscriptions.
*/
subscriptions?: SubscriptionInfo[];
subscriptions?: LinkedSubscription[];
}
/**
* @interface OptionalAuthFileParameters - Describes optional parameters for login withAuthFile.
* @interface LoginWithAuthFileOptions - Describes optional parameters for login withAuthFile.
*/
export interface OptionalAuthFileParameters {
export interface LoginWithAuthFileOptions {
/**
* @property {string} [filePath] - Absolute file path to the auth file. If not provided
* then please set the environment variable AZURE_AUTH_LOCATION.
@ -88,15 +108,15 @@ export interface OptionalAuthFileParameters {
filePath?: string;
/**
* @property {string} [subscriptionEnvVariableName] - The subscriptionId environment variable
* name. Default is 'AZURE_SUBSCRIPTION_ID'.
* name. Default is "AZURE_SUBSCRIPTION_ID".
*/
subscriptionEnvVariableName?: string;
}
/**
* @interface OptionalMSIParameters - Describes optional parameters for MSI authentication.
* @interface LoginWithMSIOptions - Describes optional parameters for MSI authentication.
*/
export interface OptionalMSIParameters {
export interface LoginWithMSIOptions {
/**
* @property {number} port - Port on which the MSI service is running on the host VM. Default port is 50342
*/
@ -115,24 +135,24 @@ export interface OptionalMSIParameters {
}
/**
* Provides a UserTokenCredentials object and the list of subscriptions associated with that userId across all the applicable tenants.
* Provides a UserTokenCredentials object and the list of subscriptions associated with that userId across all the applicable tenants.
* This method is applicable only for organizational ids that are not 2FA enabled otherwise please use interactive login.
*
* @param {string} username The user name for the Organization Id account.
* @param {string} password The password for the Organization Id account.
* @param {object} [options] Object representing optional parameters.
* @param {string} [options.clientId] The active directory application client id.
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* @param {string} [options.clientId] The active directory application client id.
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* for an example.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is 'graph'. If tokenAudience is provided
* 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).
* @param {string} [options.domain] The domain or tenant id containing this application. Default value 'common'.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is "graph". If tokenAudience is provided
* 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).
* @param {string} [options.domain] The domain or tenant id containing this application. Default value "common".
* @param {AzureEnvironment} [options.environment] The azure environment to authenticate with.
* @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal.
*
* @returns {Promise<AuthResponse>} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error.
*/
export async function withUsernamePasswordWithAuthResponse(username: string, password: string, options?: OptionalUsernamePasswordParameters): Promise<AuthResponse> {
export async function withUsernamePasswordWithAuthResponse(username: string, password: string, options?: LoginWithUsernamePasswordOptions): Promise<AuthResponse> {
if (!options) {
options = {};
}
@ -145,7 +165,7 @@ export async function withUsernamePasswordWithAuthResponse(username: string, pas
let creds: UserTokenCredentials;
let result: TokenResponse;
let tenantList: string[] = [];
let subscriptionList: SubscriptionInfo[] = [];
let subscriptionList: LinkedSubscription[] = [];
try {
creds = new UserTokenCredentials(options.clientId, options.domain, username, password, options.tokenAudience, options.environment);
result = await creds.getToken();
@ -170,19 +190,19 @@ export async function withUsernamePasswordWithAuthResponse(username: string, pas
* @param {string} secret The application secret for the service principal.
* @param {string} domain The domain or tenant id containing this application.
* @param {object} [options] Object representing optional parameters.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is 'graph'.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is "graph".
* @param {AzureEnvironment} [options.environment] The azure environment to authenticate with.
* @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal.
*
* @returns {Promise<AuthResponse>} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error.
*/
export async function withServicePrincipalSecretWithAuthResponse(clientId: string, secret: string, domain: string, options?: OptionalServicePrincipalParameters): Promise<AuthResponse> {
export async function withServicePrincipalSecretWithAuthResponse(clientId: string, secret: string, domain: string, options?: AzureTokenCredentialsOptions): Promise<AuthResponse> {
if (!options) {
options = {};
}
let creds: ApplicationTokenCredentials;
let result: TokenResponse;
let subscriptionList: SubscriptionInfo[] = [];
let subscriptionList: LinkedSubscription[] = [];
try {
creds = new ApplicationTokenCredentials(clientId, domain, secret, options.tokenAudience, options.environment);
result = await creds.getToken();
@ -198,10 +218,10 @@ export async function withServicePrincipalSecretWithAuthResponse(clientId: strin
function validateAuthFileContent(credsObj: any, filePath: string) {
if (!credsObj) {
throw new Error('Please provide a credsObj to validate.');
throw new Error("Please provide a credsObj to validate.");
}
if (!filePath) {
throw new Error('Please provide a filePath.');
throw new Error("Please provide a filePath.");
}
if (!credsObj.clientId) {
throw new Error(`"clientId" is missing from the auth file: ${filePath}.`);
@ -230,16 +250,16 @@ function validateAuthFileContent(credsObj: any, filePath: string) {
}
function foundManagementEndpointUrl(authFileUrl: string, envUrl: string): boolean {
if (!authFileUrl || (authFileUrl && typeof authFileUrl.valueOf() !== 'string')) {
throw new Error('authFileUrl cannot be null or undefined and must be of type string.');
if (!authFileUrl || (authFileUrl && typeof authFileUrl.valueOf() !== "string")) {
throw new Error("authFileUrl cannot be null or undefined and must be of type string.");
}
if (!envUrl || (envUrl && typeof envUrl.valueOf() !== 'string')) {
throw new Error('envUrl cannot be null or undefined and must be of type string.');
if (!envUrl || (envUrl && typeof envUrl.valueOf() !== "string")) {
throw new Error("envUrl cannot be null or undefined and must be of type string.");
}
authFileUrl = authFileUrl.endsWith('/') ? authFileUrl.slice(0, -1) : authFileUrl;
envUrl = envUrl.endsWith('/') ? envUrl.slice(0, -1) : envUrl;
authFileUrl = authFileUrl.endsWith("/") ? authFileUrl.slice(0, -1) : authFileUrl;
envUrl = envUrl.endsWith("/") ? envUrl.slice(0, -1) : envUrl;
return (authFileUrl.toLowerCase() === envUrl.toLowerCase());
}
@ -249,35 +269,36 @@ function foundManagementEndpointUrl(authFileUrl: string, envUrl: string): boolea
* 1. az cloud list
* 2. az cloud set n <name of the environment>
* 3. az ad sp create-for-rbac --sdk-auth > auth.json
*
*
* If the service principal is already created then login with service principal info:
* 3. az login --service-principal -u <clientId> -p <clientSecret> -t <tenantId>
* 4. az account show --sdk-auth > auth.json
*
* Authenticates using the service principal information provided in the auth file. This method will set
* the subscriptionId from the auth file to the user provided environment variable in the options
* parameter or the default 'AZURE_SUBSCRIPTION_ID'.
*
* 4. az account show --sdk-auth > auth.json
*
* Authenticates using the service principal information provided in the auth file. This method will set
* the subscriptionId from the auth file to the user provided environment variable in the options
* parameter or the default "AZURE_SUBSCRIPTION_ID".
*
* @param {object} [options] - Optional parameters
* @param {string} [options.filePath] - Absolute file path to the auth file. If not provided
* @param {string} [options.filePath] - Absolute file path to the auth file. If not provided
* then please set the environment variable AZURE_AUTH_LOCATION.
* @param {string} [options.subscriptionEnvVariableName] - The subscriptionId environment variable
* name. Default is 'AZURE_SUBSCRIPTION_ID'.
* @param {string} [options.subscriptionEnvVariableName] - The subscriptionId environment variable
* name. Default is "AZURE_SUBSCRIPTION_ID".
* @param {function} [optionalCallback] The optional callback.
*
*
* @returns {Promise<AuthResponse>} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error.
*/
export async function withAuthFileWithAuthResponse(options?: OptionalAuthFileParameters): Promise<AuthResponse> {
if (!options) options = { filePath: '' };
let filePath = options.filePath || process.env[AuthConstants.AZURE_AUTH_LOCATION];
let subscriptionEnvVariableName = options.subscriptionEnvVariableName || 'AZURE_SUBSCRIPTION_ID';
export async function withAuthFileWithAuthResponse(options?: LoginWithAuthFileOptions): Promise<AuthResponse> {
if (!options) options = { filePath: "" };
const filePath = options.filePath || process.env[AuthConstants.AZURE_AUTH_LOCATION];
const subscriptionEnvVariableName = options.subscriptionEnvVariableName || "AZURE_SUBSCRIPTION_ID";
if (!filePath) {
let msg = `Either provide an absolute file path to the auth file or set/export the environment variable - ${AuthConstants.AZURE_AUTH_LOCATION}.`;
const msg = `Either provide an absolute file path to the auth file or set/export the environment variable - ${AuthConstants.AZURE_AUTH_LOCATION}.`;
return Promise.reject(new Error(msg));
}
let content: string, credsObj: any = {}, optionsForSpSecret: any = {};
let content: string, credsObj: any = {};
const optionsForSpSecret: any = {};
try {
content = fs.readFileSync(filePath, { encoding: 'utf8' });
content = fs.readFileSync(filePath, { encoding: "utf8" });
credsObj = JSON.parse(content);
validateAuthFileContent(credsObj, filePath);
} catch (err) {
@ -287,16 +308,16 @@ export async function withAuthFileWithAuthResponse(options?: OptionalAuthFilePar
if (!credsObj.managementEndpointUrl) {
credsObj.managementEndpointUrl = credsObj.resourceManagerEndpointUrl;
}
//setting the subscriptionId from auth file to the environment variable
// setting the subscriptionId from auth file to the environment variable
process.env[subscriptionEnvVariableName] = credsObj.subscriptionId;
//get the AzureEnvironment or create a new AzureEnvironment based on the info provided in the auth file
let envFound: any = {
name: ''
// get the AzureEnvironment or create a new AzureEnvironment based on the info provided in the auth file
const envFound: any = {
name: ""
};
let envNames = Object.keys(AzureEnvironment);
const envNames = Object.keys(AzureEnvironment);
for (let i = 0; i < envNames.length; i++) {
let env = envNames[i];
let environmentObj = (AzureEnvironment as any)[env];
const env = envNames[i];
const environmentObj = (AzureEnvironment as any)[env];
if (environmentObj &&
environmentObj.managementEndpointUrl &&
foundManagementEndpointUrl(credsObj.managementEndpointUrl, environmentObj.managementEndpointUrl)) {
@ -307,17 +328,17 @@ export async function withAuthFileWithAuthResponse(options?: OptionalAuthFilePar
if (envFound.name) {
optionsForSpSecret.environment = (AzureEnvironment as any)[envFound.name];
} else {
//create a new environment with provided info.
let envParams: any = {
//try to find a logical name or set the filepath as the env name.
// create a new environment with provided info.
const envParams: any = {
// try to find a logical name or set the filepath as the env name.
name: credsObj.managementEndpointUrl.match(/.*management\.core\.(.*)\..*/i)[1] || filePath
};
let keys = Object.keys(credsObj);
const keys = Object.keys(credsObj);
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
const key = keys[i];
if (key.match(/^(clientId|clientSecret|subscriptionId|tenantId)$/ig) === null) {
if (key === 'activeDirectoryEndpointUrl' && !key.endsWith('/')) {
envParams[key] = credsObj[key] + '/';
if (key === "activeDirectoryEndpointUrl" && !key.endsWith("/")) {
envParams[key] = credsObj[key] + "/";
} else {
envParams[key] = credsObj[key];
}
@ -327,7 +348,7 @@ export async function withAuthFileWithAuthResponse(options?: OptionalAuthFilePar
envParams.activeDirectoryResourceId = credsObj.managementEndpointUrl;
}
if (!envParams.portalUrl) {
envParams.portalUrl = 'https://portal.azure.com';
envParams.portalUrl = "https://portal.azure.com";
}
optionsForSpSecret.environment = AzureEnvironment.add(envParams);
}
@ -336,25 +357,25 @@ export async function withAuthFileWithAuthResponse(options?: OptionalAuthFilePar
/**
* Provides a url and code that needs to be copy and pasted in a browser and authenticated over there. If successful, the user will get a
* Provides a url and code that needs to be copy and pasted in a browser and authenticated over there. If successful, the user will get a
* DeviceTokenCredentials object and the list of subscriptions associated with that userId across all the applicable tenants.
*
* @param {object} [options] Object representing optional parameters.
*
* @param {string} [options.clientId] The active directory application client id.
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* for an example.
*
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is 'graph'.If tokenAudience is provided
* then domain should also be provided its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is "graph".If tokenAudience is provided
* then domain should also be provided its value should not be the default "common" tenant. It must be a string (preferrably in a guid format).
*
* @param {string} [options.domain] The domain or tenant id containing this application. Default value is 'common'.
* @param {string} [options.domain] The domain or tenant id containing this application. Default value is "common".
*
* @param {AzureEnvironment} [options.environment] The azure environment to authenticate with. Default environment is "Public Azure".
*
* @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal.
*
* @param {object} [options.language] The language code specifying how the message should be localized to. Default value 'en-us'.
* @param {object} [options.language] The language code specifying how the message should be localized to. Default value "en-us".
*
* @param {object|function} [options.userCodeResponseLogger] A logger that logs the user code response message required for interactive login. When
* this option is specified the usercode response message will not be logged to console.
@ -363,7 +384,7 @@ export async function withAuthFileWithAuthResponse(options?: OptionalAuthFilePar
*
* @returns {Promise<AuthResponse>} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error.
*/
export async function withInteractiveWithAuthResponse(options?: OptionalInteractiveParameters): Promise<AuthResponse> {
export async function withInteractiveWithAuthResponse(options?: InteractiveLoginOptions): Promise<AuthResponse> {
if (!options) {
options = {};
}
@ -389,7 +410,7 @@ export async function withInteractiveWithAuthResponse(options?: OptionalInteract
if (!options.language) {
options.language = AuthConstants.DEFAULT_LANGUAGE;
}
let interactiveOptions: any = {};
const interactiveOptions: any = {};
interactiveOptions.tokenAudience = options.tokenAudience;
interactiveOptions.environment = options.environment;
interactiveOptions.domain = options.domain;
@ -397,12 +418,12 @@ export async function withInteractiveWithAuthResponse(options?: OptionalInteract
interactiveOptions.tokenCache = options.tokenCache;
interactiveOptions.language = options.language;
interactiveOptions.userCodeResponseLogger = options.userCodeResponseLogger;
let authorityUrl: string = interactiveOptions.environment.activeDirectoryEndpointUrl + interactiveOptions.domain;
let authContext: any = new adal.AuthenticationContext(authorityUrl, interactiveOptions.environment.validateAuthority, interactiveOptions.tokenCache);
const authorityUrl: string = interactiveOptions.environment.activeDirectoryEndpointUrl + interactiveOptions.domain;
const authContext: any = new adal.AuthenticationContext(authorityUrl, interactiveOptions.environment.validateAuthority, interactiveOptions.tokenCache);
interactiveOptions.context = authContext;
let userCodeResponse: any;
let creds: DeviceTokenCredentials;
let getUserCode = new Promise<any>((resolve, reject) => {
const getUserCode = new Promise<any>((resolve, reject) => {
return authContext.acquireUserCode(interactiveOptions.environment.activeDirectoryResourceId, interactiveOptions.clientId, interactiveOptions.language, (err: Error, userCodeRes: any) => {
if (err) {
return reject(err);
@ -417,7 +438,7 @@ export async function withInteractiveWithAuthResponse(options?: OptionalInteract
});
});
function getSubscriptions(creds: DeviceTokenCredentials, tenants: string[]): Promise<SubscriptionInfo[]> {
function getSubscriptions(creds: DeviceTokenCredentials, tenants: string[]): Promise<LinkedSubscription[]> {
if (!(interactiveOptions.tokenAudience && interactiveOptions.tokenAudience === TokenAudience.graph)) {
return getSubscriptionsFromTenants(creds, tenants);
}
@ -456,24 +477,24 @@ export async function withInteractiveWithAuthResponse(options?: OptionalInteract
* 1. az cloud list
* 2. az cloud set n <name of the environment>
* 3. az ad sp create-for-rbac --sdk-auth > auth.json
*
*
* If the service principal is already created then login with service principal info:
* 3. az login --service-principal -u <clientId> -p <clientSecret> -t <tenantId>
* 4. az account show --sdk-auth > auth.json
*
* Authenticates using the service principal information provided in the auth file. This method will set
* the subscriptionId from the auth file to the user provided environment variable in the options
* parameter or the default 'AZURE_SUBSCRIPTION_ID'.
*
* 4. az account show --sdk-auth > auth.json
*
* Authenticates using the service principal information provided in the auth file. This method will set
* the subscriptionId from the auth file to the user provided environment variable in the options
* parameter or the default "AZURE_SUBSCRIPTION_ID".
*
* @param {object} [options] - Optional parameters
* @param {string} [options.filePath] - Absolute file path to the auth file. If not provided
* @param {string} [options.filePath] - Absolute file path to the auth file. If not provided
* then please set the environment variable AZURE_AUTH_LOCATION.
* @param {string} [options.subscriptionEnvVariableName] - The subscriptionId environment variable
* name. Default is 'AZURE_SUBSCRIPTION_ID'.
* @param {string} [options.subscriptionEnvVariableName] - The subscriptionId environment variable
* name. Default is "AZURE_SUBSCRIPTION_ID".
* @param {function} [optionalCallback] The optional callback.
*
*
* @returns {function | Promise} If a callback was passed as the last parameter then it returns the callback else returns a Promise.
*
*
* {function} optionalCallback(err, credentials)
* {Error} [err] - The Error object if an error occurred, null otherwise.
* {ApplicationTokenCredentials} [credentials] - The ApplicationTokenCredentials object.
@ -483,15 +504,15 @@ export async function withInteractiveWithAuthResponse(options?: OptionalInteract
* @reject {Error} - The error object.
*/
export function withAuthFile(): Promise<TokenCredentialsBase>;
export function withAuthFile(options: OptionalAuthFileParameters): Promise<TokenCredentialsBase>;
export function withAuthFile(options: OptionalAuthFileParameters, callback: Function): void
export function withAuthFile(callback: any): void
export function withAuthFile(options?: OptionalAuthFileParameters, callback?: Function): any {
if (!callback && typeof options === 'function') {
export function withAuthFile(options: LoginWithAuthFileOptions): Promise<TokenCredentialsBase>;
export function withAuthFile(options: LoginWithAuthFileOptions, callback: { (err: Error, credentials: ApplicationTokenCredentials, subscriptions: Array<LinkedSubscription>): void }): void;
export function withAuthFile(callback: any): void;
export function withAuthFile(options?: LoginWithAuthFileOptions, callback?: { (err: Error, credentials: ApplicationTokenCredentials, subscriptions: Array<LinkedSubscription>): void }): any {
if (!callback && typeof options === "function") {
callback = options;
options = undefined;
}
let cb = callback as Function;
const cb = callback as Function;
if (!callback) {
return withAuthFileWithAuthResponse(options).then((authRes) => {
return Promise.resolve(authRes.credentials);
@ -503,31 +524,31 @@ export function withAuthFile(options?: OptionalAuthFileParameters, callback?: Fu
if (err) {
return cb(err);
}
return cb(null, authRes.credentials, authRes.subscriptions);
return cb(undefined, authRes.credentials, authRes.subscriptions);
});
}
}
/**
* Provides a url and code that needs to be copy and pasted in a browser and authenticated over there. If successful, the user will get a
* Provides a url and code that needs to be copy and pasted in a browser and authenticated over there. If successful, the user will get a
* DeviceTokenCredentials object and the list of subscriptions associated with that userId across all the applicable tenants.
*
* @param {object} [options] Object representing optional parameters.
* @param {string} [options.clientId] The active directory application client id.
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* for an example.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is 'graph'.If tokenAudience is provided
* then domain should also be provided its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).
* @param {string} [options.domain] The domain or tenant id containing this application. Default value is 'common'.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is "graph".If tokenAudience is provided
* then domain should also be provided its value should not be the default "common" tenant. It must be a string (preferrably in a guid format).
* @param {string} [options.domain] The domain or tenant id containing this application. Default value is "common".
* @param {AzureEnvironment} [options.environment] The azure environment to authenticate with. Default environment is "Public Azure".
* @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal.
* @param {object} [options.language] The language code specifying how the message should be localized to. Default value 'en-us'.
* @param {object} [options.language] The language code specifying how the message should be localized to. Default value "en-us".
* @param {object|function} [options.userCodeResponseLogger] A logger that logs the user code response message required for interactive login. When
* this option is specified the usercode response message will not be logged to console.
* @param {function} [optionalCallback] The optional callback.
*
*
* @returns {function | Promise} If a callback was passed as the last parameter then it returns the callback else returns a Promise.
*
*
* {function} optionalCallback(err, credentials)
* {Error} [err] - The Error object if an error occurred, null otherwise.
* {DeviceTokenCredentials} [credentials] - The DeviceTokenCredentials object.
@ -537,15 +558,15 @@ export function withAuthFile(options?: OptionalAuthFileParameters, callback?: Fu
* @reject {Error} - The error object.
*/
export function interactive(): Promise<TokenCredentialsBase>;
export function interactive(options: OptionalInteractiveParameters): Promise<TokenCredentialsBase>;
export function interactive(options: OptionalInteractiveParameters, callback: Function): void
export function interactive(callback: any): void
export function interactive(options?: OptionalInteractiveParameters, callback?: Function): any {
if (!callback && typeof options === 'function') {
export function interactive(options: InteractiveLoginOptions): Promise<TokenCredentialsBase>;
export function interactive(options: InteractiveLoginOptions, callback: { (err: Error, credentials: DeviceTokenCredentials, subscriptions: Array<LinkedSubscription>): void }): void;
export function interactive(callback: any): void;
export function interactive(options?: InteractiveLoginOptions, callback?: { (err: Error, credentials: DeviceTokenCredentials, subscriptions: Array<LinkedSubscription>): void }): any {
if (!callback && typeof options === "function") {
callback = options;
options = undefined;
}
let cb = callback as Function;
const cb = callback as Function;
if (!callback) {
return withInteractiveWithAuthResponse(options).then((authRes) => {
return Promise.resolve(authRes.credentials);
@ -557,7 +578,7 @@ export function interactive(options?: OptionalInteractiveParameters, callback?:
if (err) {
return cb(err);
}
return cb(null, authRes.credentials, authRes.subscriptions);
return cb(undefined, authRes.credentials, authRes.subscriptions);
});
}
}
@ -565,19 +586,19 @@ export function interactive(options?: OptionalInteractiveParameters, callback?:
/**
* Provides an ApplicationTokenCredentials object and the list of subscriptions associated with that servicePrinicpalId/clientId across all the applicable tenants.
*
* @param {string} clientId The active directory application client id also known as the SPN (ServicePrincipal Name).
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* @param {string} clientId The active directory application client id also known as the SPN (ServicePrincipal Name).
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* for an example.
* @param {string} secret The application secret for the service principal.
* @param {string} domain The domain or tenant id containing this application.
* @param {object} [options] Object representing optional parameters.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is 'graph'.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is "graph".
* @param {AzureEnvironment} [options.environment] The azure environment to authenticate with.
* @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal.
* @param {function} [optionalCallback] The optional callback.
*
*
* @returns {function | Promise} If a callback was passed as the last parameter then it returns the callback else returns a Promise.
*
*
* {function} optionalCallback(err, credentials)
* {Error} [err] - The Error object if an error occurred, null otherwise.
* {ApplicationTokenCredentials} [credentials] - The ApplicationTokenCredentials object.
@ -587,15 +608,15 @@ export function interactive(options?: OptionalInteractiveParameters, callback?:
* @reject {Error} - The error object.
*/
export function withServicePrincipalSecret(clientId: string, secret: string, domain: string): Promise<TokenCredentialsBase>;
export function withServicePrincipalSecret(clientId: string, secret: string, domain: string, options: OptionalServicePrincipalParameters): Promise<TokenCredentialsBase>;
export function withServicePrincipalSecret(clientId: string, secret: string, domain: string, options: OptionalServicePrincipalParameters, callback: Function): void
export function withServicePrincipalSecret(clientId: string, secret: string, domain: string, options: AzureTokenCredentialsOptions): Promise<TokenCredentialsBase>;
export function withServicePrincipalSecret(clientId: string, secret: string, domain: string, options: AzureTokenCredentialsOptions, callback: { (err: Error, credentials: ApplicationTokenCredentials, subscriptions: Array<LinkedSubscription>): void }): void;
export function withServicePrincipalSecret(clientId: string, secret: string, domain: string, callback: any): void;
export function withServicePrincipalSecret(clientId: string, secret: string, domain: string, options?: OptionalServicePrincipalParameters, callback?: Function): any {
if (!callback && typeof options === 'function') {
export function withServicePrincipalSecret(clientId: string, secret: string, domain: string, options?: AzureTokenCredentialsOptions, callback?: { (err: Error, credentials: ApplicationTokenCredentials, subscriptions: Array<LinkedSubscription>): void }): any {
if (!callback && typeof options === "function") {
callback = options;
options = undefined;
}
let cb = callback as Function;
const cb = callback as Function;
if (!callback) {
return withServicePrincipalSecretWithAuthResponse(clientId, secret, domain, options).then((authRes) => {
return Promise.resolve(authRes.credentials);
@ -607,30 +628,30 @@ export function withServicePrincipalSecret(clientId: string, secret: string, dom
if (err) {
return cb(err);
}
return cb(null, authRes.credentials, authRes.subscriptions);
return cb(undefined, authRes.credentials, authRes.subscriptions);
});
}
}
/**
* Provides a UserTokenCredentials object and the list of subscriptions associated with that userId across all the applicable tenants.
* Provides a UserTokenCredentials object and the list of subscriptions associated with that userId across all the applicable tenants.
* This method is applicable only for organizational ids that are not 2FA enabled otherwise please use interactive login.
*
* @param {string} username The user name for the Organization Id account.
* @param {string} password The password for the Organization Id account.
* @param {object} [options] Object representing optional parameters.
* @param {string} [options.clientId] The active directory application client id.
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* @param {string} [options.clientId] The active directory application client id.
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* for an example.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is 'graph'. If tokenAudience is provided
* 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).
* @param {string} [options.domain] The domain or tenant id containing this application. Default value 'common'.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is "graph". If tokenAudience is provided
* 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).
* @param {string} [options.domain] The domain or tenant id containing this application. Default value "common".
* @param {AzureEnvironment} [options.environment] The azure environment to authenticate with.
* @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal.
* @param {function} [optionalCallback] The optional callback.
*
* @returns {function | Promise} If a callback was passed as the last parameter then it returns the callback else returns a Promise.
*
*
* {function} optionalCallback(err, credentials)
* {Error} [err] - The Error object if an error occurred, null otherwise.
* {UserTokenCredentials} [credentials] - The UserTokenCredentials object.
@ -640,15 +661,15 @@ export function withServicePrincipalSecret(clientId: string, secret: string, dom
* @reject {Error} - The error object.
*/
export function withUsernamePassword(username: string, password: string): Promise<TokenCredentialsBase>;
export function withUsernamePassword(username: string, password: string, options: OptionalUsernamePasswordParameters): Promise<TokenCredentialsBase>;
export function withUsernamePassword(username: string, password: string, options: LoginWithUsernamePasswordOptions): Promise<TokenCredentialsBase>;
export function withUsernamePassword(username: string, password: string, callback: any): void;
export function withUsernamePassword(username: string, password: string, options: OptionalUsernamePasswordParameters, callback: Function): void;
export function withUsernamePassword(username: string, password: string, options?: OptionalUsernamePasswordParameters, callback?: Function): any {
if (!callback && typeof options === 'function') {
export function withUsernamePassword(username: string, password: string, options: LoginWithUsernamePasswordOptions, callback: { (err: Error, credentials: UserTokenCredentials, subscriptions: Array<LinkedSubscription>): void }): void;
export function withUsernamePassword(username: string, password: string, options?: LoginWithUsernamePasswordOptions, callback?: { (err: Error, credentials: UserTokenCredentials, subscriptions: Array<LinkedSubscription>): void }): any {
if (!callback && typeof options === "function") {
callback = options;
options = undefined;
}
let cb = callback as Function;
const cb = callback as Function;
if (!callback) {
return withUsernamePasswordWithAuthResponse(username, password, options).then((authRes) => {
return Promise.resolve(authRes.credentials);
@ -660,22 +681,22 @@ export function withUsernamePassword(username: string, password: string, options
if (err) {
return cb(err);
}
return cb(null, authRes.credentials, authRes.subscriptions);
return cb(undefined, authRes.credentials, authRes.subscriptions);
});
}
}
/**
* Initializes MSITokenCredentials class and calls getToken and returns a token response.
*
* @param {string} domain -- required. The tenant id.
* @param {object} options -- Optional parameters
*
* @param {string} domain - required. The tenant id.
* @param {object} options - Optional parameters
* @param {string} [options.port] - port on which the MSI service is running on the host VM. Default port is 50342
* @param {string} [options.resource] - The resource uri or token audience for which the token is needed. Default - "https://management.azure.com"
* @param {string} [options.aadEndpoint] - The add endpoint for authentication. default - "https://login.microsoftonline.com"
* @param {any} callback - the callback function.
*/
function _withMSI(domain: string, options?: OptionalMSIParameters): Promise<MSITokenResponse> {
function _withMSI(domain: string, options?: LoginWithMSIOptions): Promise<MSITokenResponse> {
if (!options) {
options = {};
}
@ -687,33 +708,33 @@ function _withMSI(domain: string, options?: OptionalMSIParameters): Promise<MSIT
* Before using this method please install az cli from https://github.com/Azure/azure-cli/releases.
* If you have an Azure virtual machine provisioned with az cli and has MSI enabled,
* you can then use this method to get auth tokens from the VM.
*
*
* To create a new VM, enable MSI, please execute this command:
* az vm create -g <resource_group_name> -n <vm_name> --assign-identity --image <os_image_name>
* Note: the above command enables a service endpoint on the host, with a default port 50342
*
*
* To enable MSI on a already provisioned VM, execute the following command:
* az vm --assign-identity -g <resource_group_name> -n <vm_name> --port <custom_port_number>
*
*
* To know more about this command, please execute:
* az vm --assign-identity -h
*
*
* Authenticates using the identity service running on an Azure virtual machine.
* This method makes a request to the authentication service hosted on the VM
* and gets back an access token.
*
*
* @param {string} [domain] - The domain or tenant id. This is a required parameter.
* @param {object} [options] - Optional parameters
* @param {string} [options.port] - port on which the MSI service is running on the host VM. Default port is 50342
* @param {string} [options.resource] - The resource uri or token audience for which the token is needed.
* For e.g. it can be:
* - resourcemanagement endpoint "https://management.azure.com"(default)
* - resourcemanagement endpoint "https://management.azure.com"(default)
* - management endpoint "https://management.core.windows.net/"
* @param {string} [options.aadEndpoint] - The add endpoint for authentication. default - "https://login.microsoftonline.com"
* @param {function} [optionalCallback] The optional callback.
*
*
* @returns {function | Promise} If a callback was passed as the last parameter then it returns the callback else returns a Promise.
*
*
* {function} optionalCallback(err, credentials)
* {Error} [err] - The Error object if an error occurred, null otherwise.
* {object} [tokenResponse] - The tokenResponse (token_type and access_token are the two important properties)
@ -722,15 +743,15 @@ function _withMSI(domain: string, options?: OptionalMSIParameters): Promise<MSIT
* @reject {Error} - The error object.
*/
export function withMSI(domain: string): Promise<MSITokenResponse>;
export function withMSI(domain: string, options: OptionalMSIParameters): Promise<MSITokenResponse>;
export function withMSI(domain: string, options: OptionalMSIParameters, callback: Function): void
export function withMSI(domain: string, callback: any): any
export function withMSI(domain: string, options?: OptionalMSIParameters, callback?: Function): any {
if (!callback && typeof options === 'function') {
export function withMSI(domain: string, options: LoginWithMSIOptions): Promise<MSITokenResponse>;
export function withMSI(domain: string, options: LoginWithMSIOptions, callback: { (err: Error, credentials: MSITokenResponse): void }): void;
export function withMSI(domain: string, callback: any): any;
export function withMSI(domain: string, options?: LoginWithMSIOptions, callback?: { (err: Error, credentials: MSITokenResponse): void }): any {
if (!callback && typeof options === "function") {
callback = options;
options = {};
}
let cb = callback as Function;
const cb = callback as Function;
if (!callback) {
return _withMSI(domain, options);
} else {
@ -738,8 +759,7 @@ export function withMSI(domain: string, options?: OptionalMSIParameters, callbac
if (err) {
return cb(err);
}
return cb(null, tokenRes);
return cb(undefined, tokenRes);
});
}
}
}

Просмотреть файл

@ -7,10 +7,10 @@ import { DeviceTokenCredentials } from "./credentials/deviceTokenCredentials";
import { UserTokenCredentials } from "./credentials/userTokenCredentials";
import { MSITokenCredentials, MSITokenResponse } from "./credentials/msiTokenCredentials";
import { AuthConstants, TokenAudience } from "./util/authConstants";
import { SubscriptionInfo, User, UserType } from "./subscriptionManagement/subscriptionUtils";
import { LinkedSubscription, LinkedUser, UserType } from "./subscriptionManagement/subscriptionUtils";
import {
AuthResponse, OptionalAuthFileParameters, OptionalInteractiveParameters,
OptionalMSIParameters, OptionalServicePrincipalParameters, OptionalUsernamePasswordParameters,
AuthResponse, LoginWithAuthFileOptions, InteractiveLoginOptions,
LoginWithMSIOptions, AzureTokenCredentialsOptions, LoginWithUsernamePasswordOptions,
interactive, withAuthFile, withAuthFileWithAuthResponse, withInteractiveWithAuthResponse,
withMSI, withServicePrincipalSecret, withServicePrincipalSecretWithAuthResponse,
withUsernamePassword, withUsernamePasswordWithAuthResponse
@ -19,8 +19,8 @@ import {
export {
TokenCredentialsBase, TokenResponse, ApplicationTokenCredentials, DeviceTokenCredentials,
UserTokenCredentials, MSITokenCredentials, MSITokenResponse, AuthConstants, TokenAudience,
AuthResponse, OptionalAuthFileParameters, OptionalInteractiveParameters, OptionalMSIParameters,
OptionalServicePrincipalParameters, OptionalUsernamePasswordParameters,
AuthResponse, LoginWithAuthFileOptions, InteractiveLoginOptions, LoginWithMSIOptions,
AzureTokenCredentialsOptions, LoginWithUsernamePasswordOptions,
interactive as interactiveLogin,
withInteractiveWithAuthResponse as interactiveLoginWithAuthResponse,
withUsernamePassword as loginWithUsernamePassword,
@ -30,5 +30,5 @@ export {
withAuthFile as loginWithAuthFile,
withAuthFileWithAuthResponse as loginWithAuthFileWithAuthResponse,
withMSI as loginWithMSI,
SubscriptionInfo, User, UserType
LinkedSubscription, LinkedUser, UserType
};

Просмотреть файл

@ -1,10 +1,10 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
import * as msRest from "ms-rest-ts";
import * as msRest from "ms-rest-js";
import { TokenCredentialsBase } from "../credentials/tokenCredentialsBase";
import { ApplicationTokenCredentials } from "../credentials/applicationTokenCredentials";
import { AuthConstants } from "../util/authConstants"
import { AuthConstants } from "../util/authConstants";
/**
* @interface UserType Provides information about user type. It can currently be "user" or "servicePrincipal".
@ -12,9 +12,9 @@ import { AuthConstants } from "../util/authConstants"
export type UserType = "user" | "servicePrincipal";
/**
* @interface User Provides information about a user from the authentication perspective.
* @interface LinkedUser Provides information about a user from the authentication perspective.
*/
export interface User {
export interface LinkedUser {
/**
* @property {string} name - The user name. For ApplicationTokenCredentials it can be the clientId or SPN.
*/
@ -22,26 +22,26 @@ export interface User {
/**
* @property {string} type - The user type. "user" | "servicePrincipal".
*/
type: UserType
type: UserType;
}
/**
* @interface SubscriptionInfo Provides information about subscription that was found
* during the authentication process. The structure of this type is different from the
* @interface LinkedSubscription Provides information about subscription that was found
* during the authentication process. The structure of this type is different from the
* subscription object that one gets by making a request to the ResourceManager API.
*/
export interface SubscriptionInfo {
export interface LinkedSubscription {
/**
* @property {string}
* @property {string} tenantId - The tenant that the subscription belongs to.
*/
readonly tenantId: string;
/**
* @property {string}
* @property {string} user - The user associated with the subscription. This could be a user or a serviceprincipal.
*/
readonly user: User;
readonly user: LinkedUser;
/**
* @property {string} environmentName - The environment name in which the subscription exists.
* Possible values: "Azure", "AzureChina", "AzureUSGovernment", "AzureGermanCloud" or
* @property {string} environmentName - The environment name in which the subscription exists.
* Possible values: "Azure", "AzureChina", "AzureUSGovernment", "AzureGermanCloud" or
* some other custom/internal environment name like "Dogfood".
*/
readonly environmentName: string;
@ -50,18 +50,29 @@ export interface SubscriptionInfo {
*/
readonly name: string;
/**
* @property {string} id - The subscription id, usually a guid.
* @property {string} id - The subscription id, usually a GUID.
*/
readonly id: string;
/**
* @property {any} any Placeholder for unknown properties
* @property {string} authorizationSource - The authorization source of the subscription: "RoleBased",
* "Legacy", "Bypassed"," Direct", "Management". It could also be a comma separated string containing
* more values "Bypassed, Direct, Management".
*/
readonly authorizationSource: string;
/**
* @property {string} state - The state of the subscription. Example values: "Enabled", "Disabled",
* "Warned", "PastDue", "Deleted".
*/
readonly state: string;
/**
* @property {any} any Placeholder for unknown properties.
*/
readonly [x: string]: any;
}
/**
* Builds an array of tenantIds.
* @param {TokenCredentialsBase} credentials
* @param {TokenCredentialsBase} credentials The credentials.
* @param {string} apiVersion default value 2016-06-01
* @returns {Promise<string[]>} resolves to an array of tenantIds and rejects with an error.
*/
@ -70,47 +81,47 @@ export async function buildTenantList(credentials: TokenCredentialsBase, apiVers
return Promise.resolve([credentials.domain]);
}
let client = new msRest.ServiceClient(credentials);
let baseUrl = credentials.environment.resourceManagerEndpointUrl;
let reqUrl = `${baseUrl}${baseUrl.endsWith('/') ? '' : '/'}tenants?api-version=${apiVersion}`;
let req: msRest.RequestPrepareOptions = {
const client = new msRest.ServiceClient(credentials);
const baseUrl = credentials.environment.resourceManagerEndpointUrl;
const reqUrl = `${baseUrl}${baseUrl.endsWith("/") ? "" : "/"}tenants?api-version=${apiVersion}`;
const req: msRest.RequestPrepareOptions = {
url: reqUrl,
method: "GET",
}
};
let res: msRest.HttpOperationResponse;
try {
res = await client.sendRequest(req);
} catch (err) {
return Promise.reject(err);
}
let result: string[] = [];
let tenants: any = res.bodyAsJson;
for (let tenant in tenants.value) {
result.push((<any>tenant).tenantId)
const result: string[] = [];
const tenants: any = res.bodyAsJson;
for (const tenant in tenants.value) {
result.push((<any>tenant).tenantId);
}
return Promise.resolve(result);
}
export async function getSubscriptionsFromTenants(credentials: TokenCredentialsBase, tenantList: string[], apiVersion = "2016-06-01"): Promise<SubscriptionInfo[]> {
let subscriptions: SubscriptionInfo[] = [];
let userType = 'user';
export async function getSubscriptionsFromTenants(credentials: TokenCredentialsBase, tenantList: string[], apiVersion = "2016-06-01"): Promise<LinkedSubscription[]> {
let subscriptions: LinkedSubscription[] = [];
let userType = "user";
let username: string;
let originalDomain = credentials.domain;
const originalDomain = credentials.domain;
if (credentials instanceof ApplicationTokenCredentials) {
userType = 'servicePrincipal';
userType = "servicePrincipal";
username = credentials.clientId;
} else {
username = (<any>credentials).username;
}
for (let tenant of tenantList) {
for (const tenant of tenantList) {
credentials.domain = tenant;
let client = new msRest.ServiceClient(credentials);
let baseUrl = credentials.environment.resourceManagerEndpointUrl;
let reqUrl = `${baseUrl}${baseUrl.endsWith('/') ? '' : '/'}subscriptions?api-version=${apiVersion}`;
let req: msRest.RequestPrepareOptions = {
const client = new msRest.ServiceClient(credentials);
const baseUrl = credentials.environment.resourceManagerEndpointUrl;
const reqUrl = `${baseUrl}${baseUrl.endsWith("/") ? "" : "/"}subscriptions?api-version=${apiVersion}`;
const req: msRest.RequestPrepareOptions = {
url: reqUrl,
method: "GET",
}
};
let res: msRest.HttpOperationResponse;
try {
res = await client.sendRequest(req);
@ -118,7 +129,7 @@ export async function getSubscriptionsFromTenants(credentials: TokenCredentialsB
return Promise.reject(err);
}
let subscriptionList: any[] = (<any>res.bodyAsJson).value;
const subscriptionList: any[] = (<any>res.bodyAsJson).value;
subscriptions = subscriptions.concat(subscriptionList.map((s: any) => {
s.tenantId = tenant;
s.user = { name: username, type: userType };

1118
package-lock.json сгенерированный Normal file

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -3,29 +3,33 @@
"author": {
"name": "Microsoft Corporation",
"email": "azsdkteam@microsoft.com",
"url": "https://github.com/Azure/azure-sdk-for-node"
"url": "https://github.com/Azure/ms-rest-nodeauth"
},
"version": "0.1.0",
"description": "Azure endpoints for different Azure Environments/Clouds.",
"description": "Azure Authentication library in node.js with type definitions.",
"tags": [
"node",
"isomorphic",
"microsoft",
"browser",
"azure",
"autorest",
"authentication",
"environment"
],
"keywords": [
"node",
"isomorphic",
"microsoft",
"browser",
"azure",
"autorest",
"authentication",
"environment"
],
"main": "./dist/lib/msRestNodeAuth.js",
"types": "./typings/lib/msRestNodeAuth.d.ts",
"dependencies": {
"ms-rest-azure-env": "azure/ms-rest-azure-env",
"ms-rest-ts": "amarzavery/ms-rest#master",
"ms-rest-azure-env": "^0.1.0",
"ms-rest-js": "^0.1.0",
"adal-node": "^0.1.22"
},
"license": "MIT",
@ -37,18 +41,19 @@
"tslint": "^5.2.0",
"typescript": "^2.5.2"
},
"homepage": "https://github.com/Azure/azure-sdk-for-node/runtime/ms-rest",
"homepage": "https://github.com/Azure/ms-rest-nodeauth",
"repository": {
"type": "git",
"url": "git@github.com:Azure/azure-sdk-for-node.git"
"url": "git@github.com:Azure/ms-rest-js.git"
},
"bugs": {
"url": "http://github.com/Azure/azure-sdk-for-node/issues"
"url": "http://github.com/Azure/ms-rest-nodeauth/issues"
},
"scripts": {
"tsc": "tsc -p tsconfig.json",
"test": "npm install && npm -s run-script unit",
"test": "npm -s run-script tslint",
"unit": "mocha -t 50000 dist/test",
"build": "npm -s run-script tsc"
"build": "npm -s run-script tsc",
"tslint": "tslint -p . -c tslint.json --exclude test/**/*.ts"
}
}

Просмотреть файл

@ -11,16 +11,16 @@ export declare class ApplicationTokenCredentials extends TokenCredentialsBase {
* @param {string} clientId The active directory application client id.
* @param {string} domain The domain or tenant id containing this application.
* @param {string} secret The authentication secret for the application.
* @param {string} [tokenAudience] The audience for which the token is requested. Valid value is 'graph'. If tokenAudience is provided
* then domain should also be provided its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).
* @param {string} [tokenAudience] The audience for which the token is requested. Valid value is "graph". If tokenAudience is provided
* then domain should also be provided its value should not be the default "common" tenant. It must be a string (preferrably in a guid format).
* @param {AzureEnvironment} [environment] The azure environment to authenticate with.
* @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal.
*/
constructor(clientId: string, domain: string, secret: string, tokenAudience?: TokenAudience, environment?: AzureEnvironment, tokenCache?: any);
/**
* Tries to get the token from cache initially. If that is unsuccessfull then it tries to get the token from ADAL.
* @returns {Promise<TokenResponse>} A promise that resolves to TokenResponse and rejects with an Error.
*/
* Tries to get the token from cache initially. If that is unsuccessfull then it tries to get the token from ADAL.
* @returns {Promise<TokenResponse>} A promise that resolves to TokenResponse and rejects with an Error.
*/
getToken(): Promise<TokenResponse>;
protected getTokenFromCache(): Promise<any>;
/**

Просмотреть файл

@ -12,10 +12,10 @@ export declare class DeviceTokenCredentials extends TokenCredentialsBase {
*
* @constructor
* @param {string} [clientId] The active directory application client id.
* @param {string} [domain] The domain or tenant id containing this application. Default value is 'common'
* @param {string} [username] The user name for account in the form: 'user@example.com'.
* @param {string} [tokenAudience] The audience for which the token is requested. Valid value is 'graph'. If tokenAudience is provided
* 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).
* @param {string} [domain] The domain or tenant id containing this application. Default value is "common"
* @param {string} [username] The user name for account in the form: "user@example.com".
* @param {string} [tokenAudience] The audience for which the token is requested. Valid value is "graph". If tokenAudience is provided
* 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).
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* for an example.
* @param {AzureEnvironment} [environment] The azure environment to authenticate with. Default environment is "Azure" popularly known as "Public Azure Cloud".

Просмотреть файл

@ -1,7 +1,19 @@
import * as msRest from "ms-rest-ts";
import * as msRest from "ms-rest-js";
/**
* @interface MSITokenResponse - Describes the MSITokenResponse.
*/
export interface MSITokenResponse {
/**
* @property {string} token_type - The token type.
*/
readonly token_type: string;
/**
* @property {string} access_token - The access token.
*/
readonly access_token: string;
/**
* @property {any} any - Placeholder for unknown properties.
*/
readonly [x: string]: any;
}
/**
@ -56,13 +68,13 @@ export declare class MSITokenCredentials {
* {object} [tokenResponse] The tokenResponse (token_type and access_token are the two important properties).
*/
getToken(): Promise<MSITokenResponse>;
prepareRequestOptions(): msRest.RequestPrepareOptions;
private prepareRequestOptions();
/**
* Signs a request with the Authentication header.
*
* @param {webResource} The WebResource to be signed.
* @param {function(error)} callback The callback function.
* @return {undefined}
*/
* Signs a request with the Authentication header.
*
* @param {webResource} The WebResource to be signed.
* @param {function(error)} callback The callback function.
* @return {undefined}
*/
signRequest(webResource: msRest.WebResource): Promise<msRest.WebResource>;
}

Просмотреть файл

@ -1,4 +1,4 @@
import { WebResource } from "ms-rest-ts";
import { WebResource } from "ms-rest-js";
import { TokenAudience } from "../util/authConstants";
export interface TokenResponse {
readonly tokenType: string;
@ -52,6 +52,19 @@ export declare abstract class TokenCredentialsBase {
}, tokenCache?: any);
protected getActiveDirectoryResourceId(): string;
protected getTokenFromCache(userName?: string): Promise<TokenResponse>;
/**
* Tries to get the token from cache initially. If that is unsuccessful then it tries to get the token from ADAL.
* @returns {Promise<TokenResponse>}
* {object} [tokenResponse] The tokenResponse (tokenType and accessToken are the two important properties).
* @memberof TokenCredentialsBase
*/
abstract getToken(): Promise<TokenResponse>;
/**
* Signs a request with the Authentication header.
*
* @param {webResource} The WebResource to be signed.
* @param {function(error)} callback The callback function.
* @return {undefined}
*/
signRequest(webResource: WebResource): Promise<WebResource>;
}

Просмотреть файл

@ -14,8 +14,8 @@ export declare class UserTokenCredentials extends TokenCredentialsBase {
* @param {string} domain The domain or tenant id containing this application.
* @param {string} username The user name for the Organization Id account.
* @param {string} password The password for the Organization Id account.
* @param {string} [tokenAudience] The audience for which the token is requested. Valid value is 'graph'. If tokenAudience is provided
* then domain should also be provided its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).
* @param {string} [tokenAudience] The audience for which the token is requested. Valid value is "graph". If tokenAudience is provided
* then domain should also be provided its value should not be the default "common" tenant. It must be a string (preferrably in a guid format).
* @param {AzureEnvironment} [environment] The azure environment to authenticate with.
* @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal.
*/

130
typings/lib/login.d.ts поставляемый
Просмотреть файл

@ -1,34 +1,56 @@
import { AzureEnvironment } from "ms-rest-azure-env";
import { TokenCredentialsBase } from "./credentials/tokenCredentialsBase";
import { ApplicationTokenCredentials } from "./credentials/applicationTokenCredentials";
import { DeviceTokenCredentials } from "./credentials/deviceTokenCredentials";
import { UserTokenCredentials } from "./credentials/userTokenCredentials";
import { TokenAudience } from "./util/authConstants";
import { SubscriptionInfo } from "./subscriptionManagement/subscriptionUtils";
import { LinkedSubscription } from "./subscriptionManagement/subscriptionUtils";
import { MSITokenResponse } from "./credentials/msiTokenCredentials";
/**
* @interface OptionalInteractiveParameters - Describes optional parameters for serviceprincipal/secret authentication.
* @interface AzureTokenCredentialsOptions - Describes optional parameters for serviceprincipal/secret authentication.
*/
export interface OptionalServicePrincipalParameters {
export interface AzureTokenCredentialsOptions {
/**
* @property {TokenAudience} [tokenAudience] - The audience for which the token is requested. Valid value is "graph". If tokenAudience is provided
* 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).
*/
tokenAudience?: TokenAudience;
/**
* @property {AzureEnvironment} [environment] - The Azure environment to authenticate with.
*/
environment?: AzureEnvironment;
/**
* @property {any} [tokenCache] - The token cache. Default value is MemoryCache from adal.
*/
tokenCache?: any;
}
/**
* @interface OptionalInteractiveParameters - Describes optional parameters for username/password authentication.
* @interface LoginWithUsernamePasswordOptions - Describes optional parameters for username/password authentication.
*/
export interface OptionalUsernamePasswordParameters extends OptionalServicePrincipalParameters {
export interface LoginWithUsernamePasswordOptions extends AzureTokenCredentialsOptions {
/**
* @property {string} [clientId] - The active directory application client id.
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* for an example.
*/
clientId?: string;
/**
* @property {string} [domain] - The domain or tenant id containing this application. Default value is "common".
*/
domain?: string;
}
/**
* @interface OptionalInteractiveParameters - Describes optional parameters for interactive authentication.
* @interface InteractiveLoginOptions - Describes optional parameters for interactive authentication.
*/
export interface OptionalInteractiveParameters extends OptionalUsernamePasswordParameters {
export interface InteractiveLoginOptions extends LoginWithUsernamePasswordOptions {
/**
* @property {object|function} [userCodeResponseLogger] A logger that logs the user code response message required for interactive login. When
* this option is specified the usercode response message will not be logged to console.
*/
userCodeResponseLogger?: any;
/**
* @property {string} [language] The language code specifying how the message should be localized to. Default value 'en-us'.
* @property {string} [language] The language code specifying how the message should be localized to. Default value "en-us".
*/
language?: string;
}
@ -41,14 +63,14 @@ export interface AuthResponse {
*/
credentials: TokenCredentialsBase;
/**
* @property {Array<SubscriptionInfo>} [subscriptions] List of associated subscriptions.
* @property {Array<LinkedSubscription>} [subscriptions] List of associated subscriptions.
*/
subscriptions?: SubscriptionInfo[];
subscriptions?: LinkedSubscription[];
}
/**
* @interface OptionalAuthFileParameters - Describes optional parameters for login withAuthFile.
* @interface LoginWithAuthFileOptions - Describes optional parameters for login withAuthFile.
*/
export interface OptionalAuthFileParameters {
export interface LoginWithAuthFileOptions {
/**
* @property {string} [filePath] - Absolute file path to the auth file. If not provided
* then please set the environment variable AZURE_AUTH_LOCATION.
@ -56,14 +78,14 @@ export interface OptionalAuthFileParameters {
filePath?: string;
/**
* @property {string} [subscriptionEnvVariableName] - The subscriptionId environment variable
* name. Default is 'AZURE_SUBSCRIPTION_ID'.
* name. Default is "AZURE_SUBSCRIPTION_ID".
*/
subscriptionEnvVariableName?: string;
}
/**
* @interface OptionalMSIParameters - Describes optional parameters for MSI authentication.
* @interface LoginWithMSIOptions - Describes optional parameters for MSI authentication.
*/
export interface OptionalMSIParameters {
export interface LoginWithMSIOptions {
/**
* @property {number} port - Port on which the MSI service is running on the host VM. Default port is 50342
*/
@ -90,15 +112,15 @@ export interface OptionalMSIParameters {
* @param {string} [options.clientId] The active directory application client id.
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* for an example.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is 'graph'. If tokenAudience is provided
* 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).
* @param {string} [options.domain] The domain or tenant id containing this application. Default value 'common'.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is "graph". If tokenAudience is provided
* 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).
* @param {string} [options.domain] The domain or tenant id containing this application. Default value "common".
* @param {AzureEnvironment} [options.environment] The azure environment to authenticate with.
* @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal.
*
* @returns {Promise<AuthResponse>} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error.
*/
export declare function withUsernamePasswordWithAuthResponse(username: string, password: string, options?: OptionalUsernamePasswordParameters): Promise<AuthResponse>;
export declare function withUsernamePasswordWithAuthResponse(username: string, password: string, options?: LoginWithUsernamePasswordOptions): Promise<AuthResponse>;
/**
* Provides an ApplicationTokenCredentials object and the list of subscriptions associated with that servicePrinicpalId/clientId across all the applicable tenants.
*
@ -108,13 +130,13 @@ export declare function withUsernamePasswordWithAuthResponse(username: string, p
* @param {string} secret The application secret for the service principal.
* @param {string} domain The domain or tenant id containing this application.
* @param {object} [options] Object representing optional parameters.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is 'graph'.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is "graph".
* @param {AzureEnvironment} [options.environment] The azure environment to authenticate with.
* @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal.
*
* @returns {Promise<AuthResponse>} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error.
*/
export declare function withServicePrincipalSecretWithAuthResponse(clientId: string, secret: string, domain: string, options?: OptionalServicePrincipalParameters): Promise<AuthResponse>;
export declare function withServicePrincipalSecretWithAuthResponse(clientId: string, secret: string, domain: string, options?: AzureTokenCredentialsOptions): Promise<AuthResponse>;
/**
* Before using this method please install az cli from https://github.com/Azure/azure-cli/releases. Then execute `az ad sp create-for-rbac --sdk-auth > ${yourFilename.json}`.
* If you want to create the sp for a different cloud/environment then please execute:
@ -128,18 +150,18 @@ export declare function withServicePrincipalSecretWithAuthResponse(clientId: str
*
* Authenticates using the service principal information provided in the auth file. This method will set
* the subscriptionId from the auth file to the user provided environment variable in the options
* parameter or the default 'AZURE_SUBSCRIPTION_ID'.
* parameter or the default "AZURE_SUBSCRIPTION_ID".
*
* @param {object} [options] - Optional parameters
* @param {string} [options.filePath] - Absolute file path to the auth file. If not provided
* then please set the environment variable AZURE_AUTH_LOCATION.
* @param {string} [options.subscriptionEnvVariableName] - The subscriptionId environment variable
* name. Default is 'AZURE_SUBSCRIPTION_ID'.
* name. Default is "AZURE_SUBSCRIPTION_ID".
* @param {function} [optionalCallback] The optional callback.
*
* @returns {Promise<AuthResponse>} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error.
*/
export declare function withAuthFileWithAuthResponse(options?: OptionalAuthFileParameters): Promise<AuthResponse>;
export declare function withAuthFileWithAuthResponse(options?: LoginWithAuthFileOptions): Promise<AuthResponse>;
/**
* Provides a url and code that needs to be copy and pasted in a browser and authenticated over there. If successful, the user will get a
* DeviceTokenCredentials object and the list of subscriptions associated with that userId across all the applicable tenants.
@ -150,16 +172,16 @@ export declare function withAuthFileWithAuthResponse(options?: OptionalAuthFileP
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* for an example.
*
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is 'graph'.If tokenAudience is provided
* then domain should also be provided its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is "graph".If tokenAudience is provided
* then domain should also be provided its value should not be the default "common" tenant. It must be a string (preferrably in a guid format).
*
* @param {string} [options.domain] The domain or tenant id containing this application. Default value is 'common'.
* @param {string} [options.domain] The domain or tenant id containing this application. Default value is "common".
*
* @param {AzureEnvironment} [options.environment] The azure environment to authenticate with. Default environment is "Public Azure".
*
* @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal.
*
* @param {object} [options.language] The language code specifying how the message should be localized to. Default value 'en-us'.
* @param {object} [options.language] The language code specifying how the message should be localized to. Default value "en-us".
*
* @param {object|function} [options.userCodeResponseLogger] A logger that logs the user code response message required for interactive login. When
* this option is specified the usercode response message will not be logged to console.
@ -168,7 +190,7 @@ export declare function withAuthFileWithAuthResponse(options?: OptionalAuthFileP
*
* @returns {Promise<AuthResponse>} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error.
*/
export declare function withInteractiveWithAuthResponse(options?: OptionalInteractiveParameters): Promise<AuthResponse>;
export declare function withInteractiveWithAuthResponse(options?: InteractiveLoginOptions): Promise<AuthResponse>;
/**
* Before using this method please install az cli from https://github.com/Azure/azure-cli/releases. Then execute `az ad sp create-for-rbac --sdk-auth > ${yourFilename.json}`.
* If you want to create the sp for a different cloud/environment then please execute:
@ -182,13 +204,13 @@ export declare function withInteractiveWithAuthResponse(options?: OptionalIntera
*
* Authenticates using the service principal information provided in the auth file. This method will set
* the subscriptionId from the auth file to the user provided environment variable in the options
* parameter or the default 'AZURE_SUBSCRIPTION_ID'.
* parameter or the default "AZURE_SUBSCRIPTION_ID".
*
* @param {object} [options] - Optional parameters
* @param {string} [options.filePath] - Absolute file path to the auth file. If not provided
* then please set the environment variable AZURE_AUTH_LOCATION.
* @param {string} [options.subscriptionEnvVariableName] - The subscriptionId environment variable
* name. Default is 'AZURE_SUBSCRIPTION_ID'.
* name. Default is "AZURE_SUBSCRIPTION_ID".
* @param {function} [optionalCallback] The optional callback.
*
* @returns {function | Promise} If a callback was passed as the last parameter then it returns the callback else returns a Promise.
@ -202,8 +224,10 @@ export declare function withInteractiveWithAuthResponse(options?: OptionalIntera
* @reject {Error} - The error object.
*/
export declare function withAuthFile(): Promise<TokenCredentialsBase>;
export declare function withAuthFile(options: OptionalAuthFileParameters): Promise<TokenCredentialsBase>;
export declare function withAuthFile(options: OptionalAuthFileParameters, callback: Function): void;
export declare function withAuthFile(options: LoginWithAuthFileOptions): Promise<TokenCredentialsBase>;
export declare function withAuthFile(options: LoginWithAuthFileOptions, callback: {
(err: Error, credentials: ApplicationTokenCredentials, subscriptions: Array<LinkedSubscription>): void;
}): void;
export declare function withAuthFile(callback: any): void;
/**
* Provides a url and code that needs to be copy and pasted in a browser and authenticated over there. If successful, the user will get a
@ -213,12 +237,12 @@ export declare function withAuthFile(callback: any): void;
* @param {string} [options.clientId] The active directory application client id.
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* for an example.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is 'graph'.If tokenAudience is provided
* then domain should also be provided its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).
* @param {string} [options.domain] The domain or tenant id containing this application. Default value is 'common'.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is "graph".If tokenAudience is provided
* then domain should also be provided its value should not be the default "common" tenant. It must be a string (preferrably in a guid format).
* @param {string} [options.domain] The domain or tenant id containing this application. Default value is "common".
* @param {AzureEnvironment} [options.environment] The azure environment to authenticate with. Default environment is "Public Azure".
* @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal.
* @param {object} [options.language] The language code specifying how the message should be localized to. Default value 'en-us'.
* @param {object} [options.language] The language code specifying how the message should be localized to. Default value "en-us".
* @param {object|function} [options.userCodeResponseLogger] A logger that logs the user code response message required for interactive login. When
* this option is specified the usercode response message will not be logged to console.
* @param {function} [optionalCallback] The optional callback.
@ -234,8 +258,10 @@ export declare function withAuthFile(callback: any): void;
* @reject {Error} - The error object.
*/
export declare function interactive(): Promise<TokenCredentialsBase>;
export declare function interactive(options: OptionalInteractiveParameters): Promise<TokenCredentialsBase>;
export declare function interactive(options: OptionalInteractiveParameters, callback: Function): void;
export declare function interactive(options: InteractiveLoginOptions): Promise<TokenCredentialsBase>;
export declare function interactive(options: InteractiveLoginOptions, callback: {
(err: Error, credentials: DeviceTokenCredentials, subscriptions: Array<LinkedSubscription>): void;
}): void;
export declare function interactive(callback: any): void;
/**
* Provides an ApplicationTokenCredentials object and the list of subscriptions associated with that servicePrinicpalId/clientId across all the applicable tenants.
@ -246,7 +272,7 @@ export declare function interactive(callback: any): void;
* @param {string} secret The application secret for the service principal.
* @param {string} domain The domain or tenant id containing this application.
* @param {object} [options] Object representing optional parameters.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is 'graph'.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is "graph".
* @param {AzureEnvironment} [options.environment] The azure environment to authenticate with.
* @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal.
* @param {function} [optionalCallback] The optional callback.
@ -262,8 +288,10 @@ export declare function interactive(callback: any): void;
* @reject {Error} - The error object.
*/
export declare function withServicePrincipalSecret(clientId: string, secret: string, domain: string): Promise<TokenCredentialsBase>;
export declare function withServicePrincipalSecret(clientId: string, secret: string, domain: string, options: OptionalServicePrincipalParameters): Promise<TokenCredentialsBase>;
export declare function withServicePrincipalSecret(clientId: string, secret: string, domain: string, options: OptionalServicePrincipalParameters, callback: Function): void;
export declare function withServicePrincipalSecret(clientId: string, secret: string, domain: string, options: AzureTokenCredentialsOptions): Promise<TokenCredentialsBase>;
export declare function withServicePrincipalSecret(clientId: string, secret: string, domain: string, options: AzureTokenCredentialsOptions, callback: {
(err: Error, credentials: ApplicationTokenCredentials, subscriptions: Array<LinkedSubscription>): void;
}): void;
export declare function withServicePrincipalSecret(clientId: string, secret: string, domain: string, callback: any): void;
/**
* Provides a UserTokenCredentials object and the list of subscriptions associated with that userId across all the applicable tenants.
@ -275,9 +303,9 @@ export declare function withServicePrincipalSecret(clientId: string, secret: str
* @param {string} [options.clientId] The active directory application client id.
* See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
* for an example.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is 'graph'. If tokenAudience is provided
* 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).
* @param {string} [options.domain] The domain or tenant id containing this application. Default value 'common'.
* @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is "graph". If tokenAudience is provided
* 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).
* @param {string} [options.domain] The domain or tenant id containing this application. Default value "common".
* @param {AzureEnvironment} [options.environment] The azure environment to authenticate with.
* @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal.
* @param {function} [optionalCallback] The optional callback.
@ -293,9 +321,11 @@ export declare function withServicePrincipalSecret(clientId: string, secret: str
* @reject {Error} - The error object.
*/
export declare function withUsernamePassword(username: string, password: string): Promise<TokenCredentialsBase>;
export declare function withUsernamePassword(username: string, password: string, options: OptionalUsernamePasswordParameters): Promise<TokenCredentialsBase>;
export declare function withUsernamePassword(username: string, password: string, options: LoginWithUsernamePasswordOptions): Promise<TokenCredentialsBase>;
export declare function withUsernamePassword(username: string, password: string, callback: any): void;
export declare function withUsernamePassword(username: string, password: string, options: OptionalUsernamePasswordParameters, callback: Function): void;
export declare function withUsernamePassword(username: string, password: string, options: LoginWithUsernamePasswordOptions, callback: {
(err: Error, credentials: UserTokenCredentials, subscriptions: Array<LinkedSubscription>): void;
}): void;
/**
* Before using this method please install az cli from https://github.com/Azure/azure-cli/releases.
* If you have an Azure virtual machine provisioned with az cli and has MSI enabled,
@ -335,6 +365,8 @@ export declare function withUsernamePassword(username: string, password: string,
* @reject {Error} - The error object.
*/
export declare function withMSI(domain: string): Promise<MSITokenResponse>;
export declare function withMSI(domain: string, options: OptionalMSIParameters): Promise<MSITokenResponse>;
export declare function withMSI(domain: string, options: OptionalMSIParameters, callback: Function): void;
export declare function withMSI(domain: string, options: LoginWithMSIOptions): Promise<MSITokenResponse>;
export declare function withMSI(domain: string, options: LoginWithMSIOptions, callback: {
(err: Error, credentials: MSITokenResponse): void;
}): void;
export declare function withMSI(domain: string, callback: any): any;

6
typings/lib/msRestNodeAuth.d.ts поставляемый
Просмотреть файл

@ -4,6 +4,6 @@ import { DeviceTokenCredentials } from "./credentials/deviceTokenCredentials";
import { UserTokenCredentials } from "./credentials/userTokenCredentials";
import { MSITokenCredentials, MSITokenResponse } from "./credentials/msiTokenCredentials";
import { AuthConstants, TokenAudience } from "./util/authConstants";
import { SubscriptionInfo, User, UserType } from "./subscriptionManagement/subscriptionUtils";
import { AuthResponse, OptionalAuthFileParameters, OptionalInteractiveParameters, OptionalMSIParameters, OptionalServicePrincipalParameters, OptionalUsernamePasswordParameters, interactive, withAuthFile, withAuthFileWithAuthResponse, withInteractiveWithAuthResponse, withMSI, withServicePrincipalSecret, withServicePrincipalSecretWithAuthResponse, withUsernamePassword, withUsernamePasswordWithAuthResponse } from "./login";
export { TokenCredentialsBase, TokenResponse, ApplicationTokenCredentials, DeviceTokenCredentials, UserTokenCredentials, MSITokenCredentials, MSITokenResponse, AuthConstants, TokenAudience, AuthResponse, OptionalAuthFileParameters, OptionalInteractiveParameters, OptionalMSIParameters, OptionalServicePrincipalParameters, OptionalUsernamePasswordParameters, interactive as interactiveLogin, withInteractiveWithAuthResponse as interactiveLoginWithAuthResponse, withUsernamePassword as loginWithUsernamePassword, withUsernamePasswordWithAuthResponse as loginWithUsernamePasswordWithAuthResponse, withServicePrincipalSecret as loginWithServicePrincipalSecret, withServicePrincipalSecretWithAuthResponse as loginWithServicePrincipalSecretWithAuthResponse, withAuthFile as loginWithAuthFile, withAuthFileWithAuthResponse as loginWithAuthFileWithAuthResponse, withMSI as loginWithMSI, SubscriptionInfo, User, UserType };
import { LinkedSubscription, LinkedUser, UserType } from "./subscriptionManagement/subscriptionUtils";
import { AuthResponse, LoginWithAuthFileOptions, InteractiveLoginOptions, LoginWithMSIOptions, AzureTokenCredentialsOptions, LoginWithUsernamePasswordOptions, interactive, withAuthFile, withAuthFileWithAuthResponse, withInteractiveWithAuthResponse, withMSI, withServicePrincipalSecret, withServicePrincipalSecretWithAuthResponse, withUsernamePassword, withUsernamePasswordWithAuthResponse } from "./login";
export { TokenCredentialsBase, TokenResponse, ApplicationTokenCredentials, DeviceTokenCredentials, UserTokenCredentials, MSITokenCredentials, MSITokenResponse, AuthConstants, TokenAudience, AuthResponse, LoginWithAuthFileOptions, InteractiveLoginOptions, LoginWithMSIOptions, AzureTokenCredentialsOptions, LoginWithUsernamePasswordOptions, interactive as interactiveLogin, withInteractiveWithAuthResponse as interactiveLoginWithAuthResponse, withUsernamePassword as loginWithUsernamePassword, withUsernamePasswordWithAuthResponse as loginWithUsernamePasswordWithAuthResponse, withServicePrincipalSecret as loginWithServicePrincipalSecret, withServicePrincipalSecretWithAuthResponse as loginWithServicePrincipalSecretWithAuthResponse, withAuthFile as loginWithAuthFile, withAuthFileWithAuthResponse as loginWithAuthFileWithAuthResponse, withMSI as loginWithMSI, LinkedSubscription, LinkedUser, UserType };

Просмотреть файл

@ -4,9 +4,9 @@ import { TokenCredentialsBase } from "../credentials/tokenCredentialsBase";
*/
export declare type UserType = "user" | "servicePrincipal";
/**
* @interface User Provides information about a user from the authentication perspective.
* @interface LinkedUser Provides information about a user from the authentication perspective.
*/
export interface User {
export interface LinkedUser {
/**
* @property {string} name - The user name. For ApplicationTokenCredentials it can be the clientId or SPN.
*/
@ -17,19 +17,19 @@ export interface User {
type: UserType;
}
/**
* @interface SubscriptionInfo Provides information about subscription that was found
* @interface LinkedSubscription Provides information about subscription that was found
* during the authentication process. The structure of this type is different from the
* subscription object that one gets by making a request to the ResourceManager API.
*/
export interface SubscriptionInfo {
export interface LinkedSubscription {
/**
* @property {string}
* @property {string} tenantId - The tenant that the subscription belongs to.
*/
readonly tenantId: string;
/**
* @property {string}
* @property {string} user - The user associated with the subscription. This could be a user or a serviceprincipal.
*/
readonly user: User;
readonly user: LinkedUser;
/**
* @property {string} environmentName - The environment name in which the subscription exists.
* Possible values: "Azure", "AzureChina", "AzureUSGovernment", "AzureGermanCloud" or
@ -41,19 +41,30 @@ export interface SubscriptionInfo {
*/
readonly name: string;
/**
* @property {string} id - The subscription id, usually a guid.
* @property {string} id - The subscription id, usually a GUID.
*/
readonly id: string;
/**
* @property {any} any Placeholder for unknown properties
* @property {string} authorizationSource - The authorization source of the subscription: "RoleBased",
* "Legacy", "Bypassed"," Direct", "Management". It could also be a comma separated string containing
* more values "Bypassed, Direct, Management".
*/
readonly authorizationSource: string;
/**
* @property {string} state - The state of the subscription. Example values: "Enabled", "Disabled",
* "Warned", "PastDue", "Deleted".
*/
readonly state: string;
/**
* @property {any} any Placeholder for unknown properties.
*/
readonly [x: string]: any;
}
/**
* Builds an array of tenantIds.
* @param {TokenCredentialsBase} credentials
* @param {TokenCredentialsBase} credentials The credentials.
* @param {string} apiVersion default value 2016-06-01
* @returns {Promise<string[]>} resolves to an array of tenantIds and rejects with an error.
*/
export declare function buildTenantList(credentials: TokenCredentialsBase, apiVersion?: string): Promise<string[]>;
export declare function getSubscriptionsFromTenants(credentials: TokenCredentialsBase, tenantList: string[], apiVersion?: string): Promise<SubscriptionInfo[]>;
export declare function getSubscriptionsFromTenants(credentials: TokenCredentialsBase, tenantList: string[], apiVersion?: string): Promise<LinkedSubscription[]>;