0

I'm using apps script to create an interaction between a spreadsheet and a website using its API. I must first authenticate with Oauth 2.0, here is the documentation:


Authentication - OAuth 2.0

Authentication is required before any other API call.

POST

/oauth/token

Body :

grant_type=client_credentials

Header :

Champ Type Description
Authorization String Autorization method "Basic" followed by your public_key and private_key in your settings > developer > API combined into a string "public_key:private_key" and encoded using Base64
Content-Type String Must be : application/x-www-form-urlencoded

Header (example) :

```
Authorization: Basic dGVzdGNsaWVudDp0ZXN0cGFzcw==
Content-Type: application/x-www-form-urlencoded
```

I'm completely new to API requests, and I don't understand how to format the request, I found this post:
Send POST request in Google Apps Script with Headers and Body

And as I understand, application/x-www-form-urlencoded is by default with UrlFetchApp, so I tried:

function authentication() {
  const ENDPOINT = 'api url'
  const CLIENT_ID = 'public key'
  const CLIENT_SECRET = 'secret key'
  const TOKEN_URL = ENDPOINT + '/oauth/token'
  const HEADERS = {
    'Authorization' : 'Basic ' + CLIENT_ID + ':' + CLIENT_SECRET
  }
  const BODY = 'grant_type=client_credentials'
  const OPTIONS = {
    'method' : 'post',
    'headers' : HEADERS
  }

  let response = UrlFetchApp.fetch(TOKEN_URL + "?" + BODY,OPTIONS)

  Logger.log(response.getContentText());

}

But I get a 404 error and know an unknown error.
I guess I'm doing something wrong at least with the body but I don't understand how to format properly the request.
Can someone help me?
Thanks

mthgn
  • 77
  • 9

1 Answers1

1

I would suggest that you refer to this documentation, Apps script has a library that allows you to use Oauth2 you can find it here.

Here is an example:

function accessProtectedResource(url, method_opt, headers_opt) {
  var service = getOAuthService();
  var maybeAuthorized = service.hasAccess();
  if (maybeAuthorized) {

    var accessToken = service.getAccessToken();
    var method = method_opt || 'get';
    var headers = headers_opt || {};
    headers['Authorization'] =
        Utilities.formatString('Bearer %s', accessToken);
    var resp = UrlFetchApp.fetch(url, {
      'headers': headers,
      'method' : method,
      'muteHttpExceptions': true, // Prevents thrown HTTP exceptions.
    });

    var code = resp.getResponseCode();
    if (code >= 200 && code < 300) {
      return resp.getContentText("utf-8"); // Success
    } else if (code == 401 || code == 403) {
       // Not fully authorized for this action.
       maybeAuthorized = false;
    } else {
       // Handle other response codes by logging them and throwing an
       // exception.
       console.error("Backend server error (%s): %s", code.toString(),
                     resp.getContentText("utf-8"));
       throw ("Backend server error: " + code);
    }
  }

  if (!maybeAuthorized) {
    // Invoke the authorization flow using the default authorization
    // prompt card.
    CardService.newAuthorizationException()
        .setAuthorizationUrl(service.getAuthorizationUrl())
        .setResourceDisplayName("Display name to show to the user")
        .throwException();
  }
}

function getOAuthService() {
  return OAuth2.createService('SERVICE_NAME')
      .setAuthorizationBaseUrl('SERVICE_AUTH_URL')
      .setTokenUrl('SERVICE_AUTH_TOKEN_URL')
      .setClientId('CLIENT_ID')
      .setClientSecret('CLIENT_SECRET')
      .setScope('SERVICE_SCOPE_REQUESTS')
      .setCallbackFunction('authCallback')
      .setCache(CacheService.getUserCache())
      .setPropertyStore(PropertiesService.getUserProperties());
}

function authCallback(callbackRequest) {
  var authorized = getOAuthService().handleCallback(callbackRequest);
  if (authorized) {
    return HtmlService.createHtmlOutput(
      'Success! <script>setTimeout(function() { top.window.close() }, 1);</script>');
  } else {
    return HtmlService.createHtmlOutput('Denied');
  }
}

/**
 * Unauthorizes the non-Google service. This is useful for OAuth
 * development/testing.  Run this method (Run > resetOAuth in the script
 * editor) to reset OAuth to re-prompt the user for OAuth.
 */
function resetOAuth() {
  getOAuthService().reset();
}
Gabriel Carballo
  • 1,278
  • 1
  • 3
  • 9
  • Thanx, I must admit I've already found this doc but I'm not able to understand it and therefore use it... but ok I'm gonna dig further – mthgn Oct 12 '22 at 07:03
  • If this answered your question, please click the accept button on the left (check icon). By doing so, other people in the community, who may have the same concern as you, will know that theirs can be resolved. If the accept button is unavailable to you, feel free to tell me. [How to accept answer](https://stackoverflow.com/help/accepted-answer) – Gabriel Carballo Oct 13 '22 at 13:25
  • Yes I know how it works thanx, your answer gave me clues to find by my self, but I can't figure yet how it works, I will accept your answer if I manage to get what I want :) – mthgn Oct 14 '22 at 08:55