Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
var authenticator = (challenge, callback) => {
// Create a new authentication context.
var context = new adalNode.AuthenticationContext(challenge.authorization);
// Use the context to acquire an authentication token.
return context.acquireTokenWithClientCredentials(challenge.resource, clientId, clientSecret, function(err, tokenResponse) {
if (err) throw err;
// Calculate the value to be set in the request's Authorization header and resume the call.
var authorizationValue = tokenResponse.tokenType + ' ' + tokenResponse.accessToken;
return callback(null, authorizationValue);
});
};
//Recording info
this.setRecordingsDirectory(__dirname + '/../recordings/' + this.testPrefix + '/');
this.suiteRecordingsFile = this.getRecordingsDirectory() + 'suite.' + this.testPrefix + '.nock.js';
this.recordingsFile = __dirname + '/../recordings/' + this.testPrefix + '.nock.js';
//test modes
this.isMocked = !process.env.NOCK_OFF;
this.isRecording = process.env.AZURE_NOCK_RECORD;
this.isPlayback = !process.env.NOCK_OFF && !process.env.AZURE_NOCK_RECORD;
//authentication info
this.subscriptionId = process.env['AZURE_SUBSCRIPTION_ID'] || 'subscription-id';
this.clientId = process.env['CLIENT_ID'] || DEFAULT_ADAL_CLIENT_ID;
this.domain = process.env['DOMAIN'] || 'domain';
this.username = process.env['AZURE_USERNAME'] || 'username@example.com';
this.password = process.env['AZURE_PASSWORD'] || 'dummypassword';
this.secret = process.env['APPLICATION_SECRET'] || 'dummysecret';
this.tokenCache = new adal.MemoryCache();
this._setCredentials();
//subscriptionId should be recorded for playback
if (!env) {
env = [];
}
env.push('AZURE_SUBSCRIPTION_ID');
// Normalize environment
this.normalizeEnvironment(env);
this.validateEnvironment();
//track & restore generated uuids to be used as part of request url, like a RBAC role assignment name
this.uuidsGenerated = [];
this.currentUuid = 0;
this.randomTestIdsGenerated = [];
this.numberOfRandomTestIdGenerated = 0;
this.mockVariables = {};
//stub necessary methods if in playback mode
function turnOnLogging() {
const log = adal.Logging;
log.setLoggingOptions(
{
level: 3, // Please use log.LOGGING_LEVEL.VERBOSE once AD TypeScript mappings are updated,
log: function (level: any, message: any, error: any) {
level;
console.info(message);
if (error) {
console.error(error);
}
}
});
}
return function (challenge, callback) {
// Function to take token Response and format a authorization value
function _formAuthorizationValue(err, tokenResponse) {
if (err) {
return callback(err);
}
// Calculate the value to be set in the request's Authorization header and resume the call.
var authorizationValue = tokenResponse.tokenType + ' ' + tokenResponse.accessToken;
return callback(null, authorizationValue);
}
// Create a new authentication context.
let context = new AuthenticationContext(challenge.authorization, true, credentials.context && credentials.context.cache);
if (credentials instanceof ApplicationTokenCredentials) {
return context.acquireTokenWithClientCredentials(
challenge.resource, credentials.clientId, credentials.secret, _formAuthorizationValue);
} else if (credentials instanceof UserTokenCredentials) {
return context.acquireTokenWithUsernamePassword(
challenge.resource, credentials.username, credentials.password, credentials.clientId, _formAuthorizationValue);
} else if (credentials instanceof DeviceTokenCredentials) {
return context.acquireToken(
challenge.resource, credentials.username, credentials.clientId, _formAuthorizationValue);
} else if (credentials instanceof MSITokenCredentials) {
return credentials.getToken(_formAuthorizationValue);
} else {
callback(new Error('credentials must be one of: ApplicationTokenCredentials, UserTokenCredentials, ' +
'DeviceTokenCredentials, MSITokenCredentials'));
}
var acquireTokenWithAuthorizationCode = (authorizationCode) => {
var authenticationContext = new AuthenticationContext(adalConfig.authorityUrl);
var p = new Promise((resolve, reject) => {
authenticationContext.acquireTokenWithAuthorizationCode(
authorizationCode,
adalConfig.redirectUri, // This URL must be the same as the redirect_uri of the original request or the reply url of the Azure AD App. Otherwise, it will throw an error.
adalConfig.resource,
adalConfig.clientId,
adalConfig.clientSecret,
(err, response) => {
if (err) {
reject('error: ' + err.message + '\n');
} else {
resolve({
return _auth;
};
// check old AUTH config from cache
let auth = (await globalConfig.get(AUTH)) as AuthResponse | null;
// if old AUTH config is not found, we trigger a new login flow
if (auth === null) {
auth = await retryLogin(auth);
} else {
const creds = auth.credentials as DeviceTokenCredentials;
const { clientId, domain, username, tokenAudience, environment } = creds;
// if old AUTH config was found, we extract and check if the required fields are valid
if (creds && clientId && domain && username && tokenAudience && environment) {
const cache = new MemoryCache();
cache.add(creds.tokenCache._entries, () => {});
// we need to regenerate a proper object from the saved credentials
auth.credentials = new DeviceTokenCredentials(
clientId,
domain,
username,
tokenAudience,
new Environment(environment),
cache
);
const token = await auth.credentials.getToken();
// if extracted token has expired, we request a new login flow
if (new Date(token.expiresOn).getTime() < Date.now()) {
logger.info(`Your stored credentials have expired; you'll have to log in again`);
//Recording info
this.setRecordingsDirectory(path.join(__dirname, '../../', `libraries/${ libraryPath }/tests/recordings/`));
this.suiteRecordingsFile = this.getRecordingsDirectory() + 'suite.' + this.testPrefix + '.nock.js';
//test modes
// dotenv reads booleans as strings, so we'll use ternary statements to conver to boolean
this.isMocked = !process.env.NOCK_OFF || process.env.NOCK_OFF != 'true' ? true : false;
this.isRecording = process.env.AZURE_NOCK_RECORD === 'true' ? true : false;
this.isPlayback = this.isMocked && !this.isRecording;
//authentication info
this.subscriptionId = process.env['AZURE_SUBSCRIPTION_ID'] || 'subscription-id';
this.clientId = process.env['CLIENT_ID'] || DEFAULT_ADAL_CLIENT_ID;
this.domain = process.env['DOMAIN'] || 'domain';
this.username = process.env['AZURE_USERNAME'] || 'username@example.com';
this.password = process.env['AZURE_PASSWORD'] || 'dummypassword';
this.secret = process.env['CLIENT_SECRET'] || 'dummysecret';
this.tokenCache = new adal.MemoryCache();
this._setCredentials();
//subscriptionId should be recorded for playback
if (!env) {
env = [];
}
env.push('AZURE_SUBSCRIPTION_ID');
// Normalize environment
this.normalizeEnvironment(env);
this.validateEnvironment();
//track & restore generated uuids to be used as part of request url, like a RBAC role assignment name
this.uuidsGenerated = [];
this.currentUuid = 0;
this.randomTestIdsGenerated = [];
this.numberOfRandomTestIdGenerated = 0;
this.mockVariables = {};
try {
if (req.cookies.authstate !== req.query.state) {
console.log('/accesstoken req.query.state:' + req.query.state);
console.log('/accesstoken req.cookies.authstate:' + req.cookies.authstate);
res.status(400).send('error: state does not match');
return;
}
if (req.query.error) {
if (typeof(req.cookies.redirect_uri) != 'undefined' && req.cookies.redirect_uri != 'undefined') {
res.redirect(req.cookies.redirect_uri);
return;
}
}
var authenticationContext = new AuthenticationContext(authorityUrl);
authenticationContext.acquireTokenWithAuthorizationCode(
req.query.code,
redirectUri,
ad_resource,
config_clientId,
config_clientSecret,
function (err, response) {
var errorMessage = '';
if (err) {
errorMessage = 'error: ' + err.message + '\n';
res.status(500).send(errorMessage);
} else {
console.log('/accesstoken get by auth code');
//console.dir(response);
req.session.ad_tenantid = response.tenantId;
req.session.ad_accesstoken = [response.tokenType, response.accessToken].join(' ');
if (!options.tokenCache) {
options.tokenCache = new adal.MemoryCache();
}
if (!options.language) {
options.language = azureConstants.DEFAULT_LANGUAGE;
}
this.tokenAudience = options.tokenAudience;
this.environment = options.environment;
this.domain = options.domain;
this.clientId = options.clientId;
this.tokenCache = options.tokenCache;
this.language = options.language;
var authorityUrl = this.environment.activeDirectoryEndpointUrl + this.domain;
this.context = new adal.AuthenticationContext(authorityUrl, this.environment.validateAuthority, this.tokenCache);
var self = this;
var tenantList = [];
async.waterfall([
//acquire usercode
function (callback) {
self.context.acquireUserCode(self.environment.activeDirectoryResourceId, self.clientId, self.language, function (err, userCodeResponse) {
if (err) return callback(err);
console.log(userCodeResponse.message);
return callback(null, userCodeResponse);
});
},
//acquire token with device code and set the username to userId received from tokenResponse.
function (userCodeResponse, callback) {
self.context.acquireTokenWithDeviceCode(self.environment.activeDirectoryResourceId, self.clientId, userCodeResponse, function (err, tokenResponse) {
if (err) return callback(err);
self.username = tokenResponse.userId;
function _turnOnLogging() {
var log = adal.Logging;
log.setLoggingOptions(
{
level : log.LOGGING_LEVEL.VERBOSE,
log : function (level, message, error) {
console.info(message);
if (error) {
console.error(error);
}
}
});
}