google-apps-script-snippets icon indicating copy to clipboard operation
google-apps-script-snippets copied to clipboard

Use cookies

Open oshliaer opened this issue 8 years ago • 2 comments

Cookie handling in Google Apps Script - How to send cookies in header?

function example() {

  Logger.log(getContacts());

}

// Some API
function getContacts() {

  auth();

  var headers = {
    'Cookie': CacheService.getUserCache().get('auth')
  };
  var params = {
    'headers': headers,
    muteHttpExceptions: true
  };
  return UrlFetchApp.fetch( /* API URL */ , params);

}

// Auth flow
function auth() {

  var cache = CacheService.getUserCache().get('auth');
  if (!cache)
    auth_();

}

function auth_() {

  var params = {};
  params.method = 'post';
  params.payload = {
    LOGIN: 'USER LOGIN',
    PWD: 'USER PASSWORD'
  };
  var fetch = UrlFetchApp.fetch( /* API URL */ , params);

  CacheService.getUserCache().put('auth', fetch.getAllHeaders()['Set-Cookie'], /* IF IT EXPIRES */ );

  return fetch;

}

oshliaer avatar Aug 29 '17 13:08 oshliaer

work!

AngelSlava avatar Jan 14 '19 14:01 AngelSlava

I'm so glad that this helps.

oshliaer avatar Jan 16 '19 07:01 oshliaer