Skip to content

Instantly share code, notes, and snippets.

@catalinmiron
Forked from tanaikech/submit.md
Created October 26, 2019 06:11
Show Gist options
  • Save catalinmiron/4c4e2afdb7bc537fa7c3b3797065d0a4 to your computer and use it in GitHub Desktop.
Save catalinmiron/4c4e2afdb7bc537fa7c3b3797065d0a4 to your computer and use it in GitHub Desktop.
Retrieving Access Token From OneDrive using Google Apps Script

Retrieving Access Token From OneDrive using Google Apps Script

Overview

This GAS sample is for retrieving access token to use OneDrive APIs using Google Apps Script.

In this script, the authorization code is automatically retrieved.

Demo

Usage

In order to use this, both accounts of Google and OneDrive (MSN) are required.

Google side

  1. Copy and paste the sample script to your script editor. You can use the standalone script for this.
  2. Deploy Web Apps.
    • On the Script Editor
      • File
      • -> Manage Versions
      • -> Save New Version
      • Publish
      • -> Deploy as Web App
      • -> At Execute the app as, select "your account"
      • -> At Who has access to the app, select "Only myself"
      • -> Click "Deploy"
      • -> Copy URL of "latest code" (This is important!)
      • -> Click "OK"
  3. URL of "latest code" is https://script.google.com/macros/s/###/dev. So please modify this URL. Replace from "dev" to "usercallback" for the URL. And copy this modified URL.
    • From : https://script.google.com/macros/s/###/dev
    • To : https://script.google.com/macros/s/###/usercallback

OneDrive side

  1. Add new application at https://apps.dev.microsoft.com.
    • Enable "Guided Setup".
  2. Retrieve application ID. This is client ID.
  3. By creating new password, retrieve application secret. This is client secret.
  4. Add platform. Select WEB.
  5. Input https://script.google.com/macros/s/###/usercallback as redirect uri. This URL is from "Google side".
  6. Click save button.

By above operation, the preparation is done.

Launch Script

In order to run the script, please launch as follows.

At first, please input "application ID" and "application secret" from OneDrive to setProp(). And run setProp().

As a next step, launch as follows.

  • On the Script Editor
    • Publish
    • -> Deploy as Web App
    • -> Click Test web app for your latest code..

Note

Refresh token can be retrieved by including offline_access in the Scope.

Script

This is Google Apps Script.

function setProp(){
 PropertiesService.getScriptProperties().setProperties({
   clientId: '### application ID ###',
   clientSecret: '### application secret ###',
   scope: "offline_access files.readwrite.all", // This is sample. So please modify for your environment.
 });
}

function doGet() {
  var prop = PropertiesService.getScriptProperties().getProperties();
  var url = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize";
  var param = {
    "response_type" : "code",
    "client_id" : prop.clientId,
    "redirect_uri" : getCallbackURL(),
    "state" : ScriptApp.newStateToken().withMethod("callback").withTimeout(300).createToken(),
    "scope" : prop.scope,
  };
  var params = [];
  for(var name in param){
    params.push(name + "=" + encodeURIComponent(param[name]));
  }
  var html = "<input type=\"button\" value=\"auth\" onclick=\"window.open('" + url + "?" + params.join("&") + "', 'Authorization', 'width=500,height=600');\">"
  return HtmlService.createHtmlOutput(html)
}

function getCallbackURL() {
  var url = ScriptApp.getService().getUrl();
  if (url.indexOf("/exec") >= 0) {
    url = url.slice(0, -4) + 'usercallback';
  }
  url = url.slice(0, -3) + 'usercallback';
  PropertiesService.getScriptProperties().setProperties({
    redirect_uri: url,
  });
  return url
}

function callback(e) {
  var credentials = fetchAccessToken(e.parameter.code);
  return HtmlService.createHtmlOutput(JSON.stringify(credentials, null, "  "));
}

function fetchAccessToken(code) {
  var prop = PropertiesService.getScriptProperties().getProperties();
  var payload = {
      "code" : code,
      "client_id" : prop.clientId,
      "client_secret" : prop.clientSecret,
      "redirect_uri" : prop.redirect_uri,
      "grant_type" : "authorization_code"
    }
  var res = UrlFetchApp.fetch("https://login.microsoftonline.com/common/oauth2/v2.0/token", {
    "method" : "POST",
    payload : payload,
    muteHttpExceptions : true
  });
  return JSON.parse(res.getContentText());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment