google-sheetsgoogle-apps-scriptoauth-2.0authorizationgoogle-oauth

How to avoid re-authorization of App Script?


I have written an apps script connected to my google spreadsheet to export it to a JSON file. The data is need in an android application that I am building and access via the Web App "/exec" link.

I want this data to be public and run without authorizing the user inside the app or in the browser. That's why I have set it to run as myself and anybody to have access to it. This works fine for about a week. After that it prompts me to re-authorize.

The apps script The deployment configuration

The code:

function doGet() {
  var sheetName = "EDIT"; // Replace with the name of your sheet
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);

  if (!sheet) {
    return {
      error: "Sheet not found."
    };
  }

  var data = sheet.getDataRange().getValues().map(([a,,c,d,e,f,g,,i,j,,,,,o,,q,r,s,t,u,v]) => [a,c,d,e,f,g,i,j,o,q,r,s,t,u,v]);
  var headers = data[0];
  var jsonData = [];

  for (var i = 1; i < data.length; i++) {
    var row = data[i];
    var rowObject = {};

    for (var j = 0; j < headers.length; j++) {
      rowObject[headers[j]] = row[j];
    }

    jsonData.push(rowObject);
  }

  console.log(jsonData)

  return ContentService.createTextOutput(JSON.stringify(jsonData))
    .setMimeType(ContentService.MimeType.JSON);
}

function myFunction() {
doGet();  
}

The appscript.json:

{
  "timeZone": "Europe/Berlin",
  "dependencies": {},
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "sheets": {
    "macros": [
      {
        "menuName": "sort",
        "functionName": "sort",
        "defaultShortcut": "Ctrl+Alt+Shift+1"
      }
    ]
  },
  "webapp": {
    "executeAs": "USER_DEPLOYING",
    "access": "ANYONE_ANONYMOUS"
  },
  "executionApi": {
    "access": "MYSELF"
  }
}

I have read online that this is a security measure by Google, but I want to avoid re-authorizing every week. I followed most advice, but still can not get it to work long term. People suggested that this is only for "Testing", but I have deployed the app and still nothing. Furthermore, I read that publishing might help, but Google requires a lot of information. Is there any solution?


Solution

  • An alternative way is to access the data through a data source URL. The default is JSON but its format differs from what the doGet() in the question outputs. CSV and HTML table format are also available.

    There are many options that can be set in the URL, including a subset of SQL for aggregating the data. See Download link for Google Spreadsheets.

    Note that the spreadsheet needs to be shared as "anyone with link can view" for the data source URL to work without authentication.

    Yet another way is to simply choose File > Share > Publish to web. Again, there are many formats available.