Reputation: 41
I'm trying to make a standalone Google Apps Script to access an API through the OAuth2 library, found here: https://github.com/googlesamples/apps-script-oauth2
I have not been able to get any of the examples to work so far, but I think it's because I cannot register my application and set the OAuth redirect URI. This is my first attempt at using OAuth.
Here are the steps I've taken:
I get the error shown at this link (which reads "You do not have permission to perform this action.
From what I've studied, I need this URI entered in order to make this script work. Why won't this save?
Upvotes: 4
Views: 5734
Reputation: 1625
Here are some things you can try.
Step one
The web app api
Change from using the appscript API to using a web app API. You can create a new one in the API admin console.
Then select the web app option.
Finally you will have a new API.
Open the new API and get the client ID and secrets.
Paste into the api the redirect from your app.
https://script.google.com/macros/d/{SCRIPT ID}/usercallback
Step two
The authentication and redirect
The next bit is tricky and may need some fiddling.
The first part of the code below generates a URL. The user then needs to be directed to open the generated URL in a new window. The new window will show all the usual google permissions including any scopes. When the user accepts they will be redirected back to your app.
function getAuthURL() {
var driveService = getDriveService();
if (!driveService.hasAccess()) {
var authorizationUrl = driveService.getAuthorizationUrl();
Logger.log(authorizationUrl)
}
function authCallback(request) {
var driveService = getDriveService();
var isAuthorized = driveService.handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('Success! You can close this tab.');
} else {
return HtmlService.createHtmlOutput('Denied. You can close this tab');
}
}
Step three
The access token
Now the user gave permission it is possible to get the access token and pass it along on with fetch requests.
function makeRequest() {
var driveService = getDriveService();
var response = UrlFetchApp.fetch('https://www.googleapis.com/drive/v2/files?maxResults=10', {
headers: {
Authorization: 'Bearer ' + driveService.getAccessToken()
}
});
// ...
}
Upvotes: 4