//config varibales const tokenLifeTime = 59;//minute pm.environment.set('tenantDomain', 'dev.onmicrosoft.com') // Directories + subscriptions pm.environment.set('client_credentials', 'client_credentials') // type pm.environment.set('clientId', 'de1d0d77-') // pm.environment.set('clientSecret', 'fUA=') // pm.environment.set('resource', 'http://dev.com/cloudservices/system/test1/agent') //ResourcesId //check bearerToken. var oldToken = pm.environment.get('bearerToken'); var bearerTime = pm.environment.get('bearerTime');//last update bearerToken time var noToken = oldToken == undefined || oldToken == null || oldToken.trim() == ''; var expired = bearerTime == undefined || (new Date(bearerTime).addMinutes(tokenLifeTime) - new Date()) < 0; if (noToken || expired) { console.log('BearerToken has expired.') pm.sendRequest( { url: 'https://login.microsoftonline.com/' + pm.environment.get('tenantDomain') + '/oauth2/token', method: 'POST', header: 'Content-Type: application/x-www-form-urlencoded', body: { mode: 'urlencoded', urlencoded: [ { key: 'grant_type', value: 'client_credentials', disabled: false }, { key: 'client_id', value: pm.environment.get('clientId'), disabled: false, }, { key: 'client_secret', value: pm.environment.get('clientSecret'), disabled: false, }, //{ key: 'scope', value: pm.environment.get('scope'), disabled: false }, { key: 'resource', value: pm.environment.get('resource'), disabled: false }, ], }, }, function (err, res) { //pm.globals.set('bearerToken', res.json().access_token) pm.environment.set('bearerToken', res.json().access_token) pm.environment.set('bearerTime', new Date()) console.log(pm.environment.get('bearerToken')) }, ) } else { console.log('BearerToken is exist and life is ok.') }
将上述代码置于左建点击某一Collection的Pre-request Script 后,再选中AuthorizationTab页修改为: