Google Script authenticate on external website

2020-04-20 04:34发布

问题:

I need to implement a google script app that is used to login on a website and then if the authentication process succeed on that website the user should receive a message in the google script sidebar.

For example: the user enters his email and password and then he press the Login button, then he should be logged in on the website if the credentials are correct.

Let me know if I need to provide more details on this...I am new with google app script and I really need some help with this login process. Thank you!

I tried to implement the following code but I receive the following error message when executing the login function: Request failed for https://example.com/login returned code 405.

HTML file:

<div class="form-auth">
  <label class="inline">username</label>
  <input type="text" placeholder="Insert Email"/>
</div>
<div class="form-auth">
  <label class="inline">password</label>
  <input placeholder="Insert Password"/>
</div>
<button class="btn-default">Login</button>

Google Script file:

function onOpen() {
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .createMenu('Menu')
      .addItem('Show sidebar', 'showSidebar')
      .addToUi();
}

function showSidebar() {
  var html = HtmlService.createHtmlOutputFromFile('login')
      .setSandboxMode(HtmlService.SandboxMode.IFRAME)
      .setTitle('SDR Tag Governance')
      .setWidth(300);
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .showSidebar(html);
}

function login() {
  var payload =
   {
     "username" : "myEmail@domain.com",
     "password" : "myPassword",
   };
  var options =
   {
     "method" : "post",
     "payload" : payload,
     "followRedirects" : false
   };
  var login = UrlFetchApp.fetch("https://example.com/login" , options);
  var sessionDetails = login.getAllHeaders()['Set-Cookie'];
}

回答1:

Fixed this by adding headers option:

  var headers = {
    'Connection':'keep-alive',
    'Content-Type':'application/json;charset=utf-8',
    'Accept':'application/json, text/plain, */*',
    'Cookie':'...',
  }