Google Apps Script OAuth2 Library Error for Service Accounts if private Key is not stored in apps script file directlyInvalid redirect url after open auth 2.0 authentication via GoogleIs it possible to be able to correctly select any available Google account to use when using authorisation via the JS client library for Drive?How to use Oauth2 service accounts with Google Drive and the App Engine SDKHow to get OAuth2 working with a service accountGoogle Apps Script - Access to different account (contact-api) via OAuth2-authenticationCan the Google Apps Script Execution API be called by a service account?gsutil OAuth2 authorization (example of .boto file is needed)How can I resolve the Google oauth2 error - 'Invalid client secret JSON file'?oauth2: Logoff currently logged in google user and then send the oauth url from my appHow to Auth to Google Cloud using Service Account in Python?

What does a comma signify in inorganic chemistry?

Can I use images from my published papers in my thesis without copyright infringment?

How to train a replacement without them knowing?

Unconventional examples of mathematical modelling

Is a suspension needed to do wheelies?

A+ rating still unsecure by Google Chrome's opinion

Why is su world executable?

Regression when x and y each have uncertainties

Do I need to start off my book by describing the character's "normal world"?

What exactly happened to the 18 crew members who were reported as "missing" in "Q Who"?

Adjective or adverb before another adjective

May the tower use the runway while an emergency aircraft is inbound?

Is the Microsoft recommendation to use C# properties applicable to game development?

Photoshop older default brushes

When and which board game was the first to be ever invented?

Quick destruction of a helium filled airship?

programming a recursive formula into Mathematica and find the nth position in the sequence

Adding things to bunches of things vs multiplication

Output with the same length always

Would getting a natural 20 with a penalty still count as a critical hit?

Number of matrices with bounded products of rows and columns

Has there ever been a truly bilingual country prior to the contemporary period?

What is the purpose/function of this power inductor in parallel?

Why can't I see 1861 / 1871 census entries on Freecen website when I can see them on Ancestry website?



Google Apps Script OAuth2 Library Error for Service Accounts if private Key is not stored in apps script file directly


Invalid redirect url after open auth 2.0 authentication via GoogleIs it possible to be able to correctly select any available Google account to use when using authorisation via the JS client library for Drive?How to use Oauth2 service accounts with Google Drive and the App Engine SDKHow to get OAuth2 working with a service accountGoogle Apps Script - Access to different account (contact-api) via OAuth2-authenticationCan the Google Apps Script Execution API be called by a service account?gsutil OAuth2 authorization (example of .boto file is needed)How can I resolve the Google oauth2 error - 'Invalid client secret JSON file'?oauth2: Logoff currently logged in google user and then send the oauth url from my appHow to Auth to Google Cloud using Service Account in Python?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















I successfully set up connection from google apps script to Google Cloud firestore database with a service account. It is working fine as long I store the credentials in the apps script file itself. If I store the private Key of the credential somewhere else (in database, in a drive file, google doc...) oauth2 authentication fails with error: "Invalid Argument: Key" thrown by GAS Oauth2 library.



I investigated further and it seems an encoding/charset problem. If I compare the length of the private Key string between hard coded and stored in a File/DB the length of the key is not equal, but the key-strings seems to be identical.



Some help would be appreciated.



function createOAuth() 

// credentials of service account hard coded
var jsonObj =
"type": "service_account",
"project_id": "id of project",
"private_key": "-----BEGIN PRIVATE KEY-----.....----END PRIVATE KEY-n",
"client_email": "servic accoutn email",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",


// not working if store attribute private_key somewhere else like:
/*var fileContent = DriveApp.getFileById('idOfFile').getBlob().getDataAsString("UTF-8"); //OR
DocumentApp.getBody().getText() //OR
var privateKey = Utilities.newBlob(privatKeyFromCredents).getDataAsString()
//store key in cloud firestore database also not working.
*/

return OAuth2.createService("Service Account")
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setPrivateKey(jsonObj.private_key)
.setIssuer(jsonObj.client_email)
.setPropertyStore(PropertiesService.getScriptProperties())
.setCache(CacheService.getScriptCache())
.setParam('access_type', 'offline')
.setScope('https://www.googleapis.com/auth/script.external_request https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/datastore');

var access = service.hasAccess(); // true if jsonObj is hard coded
// false if stored somewhere else --> error: Invalid Argument: Key
Logger.log('Access: ' + access);











share|improve this question



















  • 1





    How about storing it in a text file or a bin file?

    – TheMaster
    Mar 27 at 12:45











  • About the commented script, if the file of idOfFile is a text file and the file content of idOfFile is -----BEGIN PRIVATE KEY-----.....----END PRIVATE KEY-n, for example, how about var privateKey = DriveApp.getFileById('idOfFile').getBlob().getDataAsString();? By the way, what is privatKeyFromCredents in your script?

    – Tanaike
    Mar 27 at 23:27











  • I tried it also to store the key in a text files (in various formats). but that also did not worked. the following code was another try to convert the key that was stored in a txt file on drive, creat than a blob and transform the key to another charset: var privateKey = Utilities.newBlob(privatKeyFromCredents).getDataAsString() but that also failed...

    – Jochen
    Mar 28 at 13:08












  • I am wonderin in what format is a hard coded string is stored in an apps script file? because the length of the key string is different if check the length of the variable where the hard coded key is stored compared to read the key in utf-8 form a google doc or text file...

    – Jochen
    Mar 28 at 13:14











  • @Jochen Thank you for replying. At first, I apologize my comment was not useful for your situation. As a next method, for example, how about directly upload the downloaded file when the service account is created to Google Drive, and use it? The file is json file. So the private key can be retrieved. Can I ask you about this?

    – Tanaike
    Mar 28 at 22:35

















2















I successfully set up connection from google apps script to Google Cloud firestore database with a service account. It is working fine as long I store the credentials in the apps script file itself. If I store the private Key of the credential somewhere else (in database, in a drive file, google doc...) oauth2 authentication fails with error: "Invalid Argument: Key" thrown by GAS Oauth2 library.



I investigated further and it seems an encoding/charset problem. If I compare the length of the private Key string between hard coded and stored in a File/DB the length of the key is not equal, but the key-strings seems to be identical.



Some help would be appreciated.



function createOAuth() 

// credentials of service account hard coded
var jsonObj =
"type": "service_account",
"project_id": "id of project",
"private_key": "-----BEGIN PRIVATE KEY-----.....----END PRIVATE KEY-n",
"client_email": "servic accoutn email",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",


// not working if store attribute private_key somewhere else like:
/*var fileContent = DriveApp.getFileById('idOfFile').getBlob().getDataAsString("UTF-8"); //OR
DocumentApp.getBody().getText() //OR
var privateKey = Utilities.newBlob(privatKeyFromCredents).getDataAsString()
//store key in cloud firestore database also not working.
*/

return OAuth2.createService("Service Account")
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setPrivateKey(jsonObj.private_key)
.setIssuer(jsonObj.client_email)
.setPropertyStore(PropertiesService.getScriptProperties())
.setCache(CacheService.getScriptCache())
.setParam('access_type', 'offline')
.setScope('https://www.googleapis.com/auth/script.external_request https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/datastore');

var access = service.hasAccess(); // true if jsonObj is hard coded
// false if stored somewhere else --> error: Invalid Argument: Key
Logger.log('Access: ' + access);











share|improve this question



















  • 1





    How about storing it in a text file or a bin file?

    – TheMaster
    Mar 27 at 12:45











  • About the commented script, if the file of idOfFile is a text file and the file content of idOfFile is -----BEGIN PRIVATE KEY-----.....----END PRIVATE KEY-n, for example, how about var privateKey = DriveApp.getFileById('idOfFile').getBlob().getDataAsString();? By the way, what is privatKeyFromCredents in your script?

    – Tanaike
    Mar 27 at 23:27











  • I tried it also to store the key in a text files (in various formats). but that also did not worked. the following code was another try to convert the key that was stored in a txt file on drive, creat than a blob and transform the key to another charset: var privateKey = Utilities.newBlob(privatKeyFromCredents).getDataAsString() but that also failed...

    – Jochen
    Mar 28 at 13:08












  • I am wonderin in what format is a hard coded string is stored in an apps script file? because the length of the key string is different if check the length of the variable where the hard coded key is stored compared to read the key in utf-8 form a google doc or text file...

    – Jochen
    Mar 28 at 13:14











  • @Jochen Thank you for replying. At first, I apologize my comment was not useful for your situation. As a next method, for example, how about directly upload the downloaded file when the service account is created to Google Drive, and use it? The file is json file. So the private key can be retrieved. Can I ask you about this?

    – Tanaike
    Mar 28 at 22:35













2












2








2


0






I successfully set up connection from google apps script to Google Cloud firestore database with a service account. It is working fine as long I store the credentials in the apps script file itself. If I store the private Key of the credential somewhere else (in database, in a drive file, google doc...) oauth2 authentication fails with error: "Invalid Argument: Key" thrown by GAS Oauth2 library.



I investigated further and it seems an encoding/charset problem. If I compare the length of the private Key string between hard coded and stored in a File/DB the length of the key is not equal, but the key-strings seems to be identical.



Some help would be appreciated.



function createOAuth() 

// credentials of service account hard coded
var jsonObj =
"type": "service_account",
"project_id": "id of project",
"private_key": "-----BEGIN PRIVATE KEY-----.....----END PRIVATE KEY-n",
"client_email": "servic accoutn email",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",


// not working if store attribute private_key somewhere else like:
/*var fileContent = DriveApp.getFileById('idOfFile').getBlob().getDataAsString("UTF-8"); //OR
DocumentApp.getBody().getText() //OR
var privateKey = Utilities.newBlob(privatKeyFromCredents).getDataAsString()
//store key in cloud firestore database also not working.
*/

return OAuth2.createService("Service Account")
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setPrivateKey(jsonObj.private_key)
.setIssuer(jsonObj.client_email)
.setPropertyStore(PropertiesService.getScriptProperties())
.setCache(CacheService.getScriptCache())
.setParam('access_type', 'offline')
.setScope('https://www.googleapis.com/auth/script.external_request https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/datastore');

var access = service.hasAccess(); // true if jsonObj is hard coded
// false if stored somewhere else --> error: Invalid Argument: Key
Logger.log('Access: ' + access);











share|improve this question














I successfully set up connection from google apps script to Google Cloud firestore database with a service account. It is working fine as long I store the credentials in the apps script file itself. If I store the private Key of the credential somewhere else (in database, in a drive file, google doc...) oauth2 authentication fails with error: "Invalid Argument: Key" thrown by GAS Oauth2 library.



I investigated further and it seems an encoding/charset problem. If I compare the length of the private Key string between hard coded and stored in a File/DB the length of the key is not equal, but the key-strings seems to be identical.



Some help would be appreciated.



function createOAuth() 

// credentials of service account hard coded
var jsonObj =
"type": "service_account",
"project_id": "id of project",
"private_key": "-----BEGIN PRIVATE KEY-----.....----END PRIVATE KEY-n",
"client_email": "servic accoutn email",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",


// not working if store attribute private_key somewhere else like:
/*var fileContent = DriveApp.getFileById('idOfFile').getBlob().getDataAsString("UTF-8"); //OR
DocumentApp.getBody().getText() //OR
var privateKey = Utilities.newBlob(privatKeyFromCredents).getDataAsString()
//store key in cloud firestore database also not working.
*/

return OAuth2.createService("Service Account")
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setPrivateKey(jsonObj.private_key)
.setIssuer(jsonObj.client_email)
.setPropertyStore(PropertiesService.getScriptProperties())
.setCache(CacheService.getScriptCache())
.setParam('access_type', 'offline')
.setScope('https://www.googleapis.com/auth/script.external_request https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/datastore');

var access = service.hasAccess(); // true if jsonObj is hard coded
// false if stored somewhere else --> error: Invalid Argument: Key
Logger.log('Access: ' + access);








google-apps-script oauth-2.0






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 27 at 12:20









Jochen Jochen

112 bronze badges




112 bronze badges










  • 1





    How about storing it in a text file or a bin file?

    – TheMaster
    Mar 27 at 12:45











  • About the commented script, if the file of idOfFile is a text file and the file content of idOfFile is -----BEGIN PRIVATE KEY-----.....----END PRIVATE KEY-n, for example, how about var privateKey = DriveApp.getFileById('idOfFile').getBlob().getDataAsString();? By the way, what is privatKeyFromCredents in your script?

    – Tanaike
    Mar 27 at 23:27











  • I tried it also to store the key in a text files (in various formats). but that also did not worked. the following code was another try to convert the key that was stored in a txt file on drive, creat than a blob and transform the key to another charset: var privateKey = Utilities.newBlob(privatKeyFromCredents).getDataAsString() but that also failed...

    – Jochen
    Mar 28 at 13:08












  • I am wonderin in what format is a hard coded string is stored in an apps script file? because the length of the key string is different if check the length of the variable where the hard coded key is stored compared to read the key in utf-8 form a google doc or text file...

    – Jochen
    Mar 28 at 13:14











  • @Jochen Thank you for replying. At first, I apologize my comment was not useful for your situation. As a next method, for example, how about directly upload the downloaded file when the service account is created to Google Drive, and use it? The file is json file. So the private key can be retrieved. Can I ask you about this?

    – Tanaike
    Mar 28 at 22:35












  • 1





    How about storing it in a text file or a bin file?

    – TheMaster
    Mar 27 at 12:45











  • About the commented script, if the file of idOfFile is a text file and the file content of idOfFile is -----BEGIN PRIVATE KEY-----.....----END PRIVATE KEY-n, for example, how about var privateKey = DriveApp.getFileById('idOfFile').getBlob().getDataAsString();? By the way, what is privatKeyFromCredents in your script?

    – Tanaike
    Mar 27 at 23:27











  • I tried it also to store the key in a text files (in various formats). but that also did not worked. the following code was another try to convert the key that was stored in a txt file on drive, creat than a blob and transform the key to another charset: var privateKey = Utilities.newBlob(privatKeyFromCredents).getDataAsString() but that also failed...

    – Jochen
    Mar 28 at 13:08












  • I am wonderin in what format is a hard coded string is stored in an apps script file? because the length of the key string is different if check the length of the variable where the hard coded key is stored compared to read the key in utf-8 form a google doc or text file...

    – Jochen
    Mar 28 at 13:14











  • @Jochen Thank you for replying. At first, I apologize my comment was not useful for your situation. As a next method, for example, how about directly upload the downloaded file when the service account is created to Google Drive, and use it? The file is json file. So the private key can be retrieved. Can I ask you about this?

    – Tanaike
    Mar 28 at 22:35







1




1





How about storing it in a text file or a bin file?

– TheMaster
Mar 27 at 12:45





How about storing it in a text file or a bin file?

– TheMaster
Mar 27 at 12:45













About the commented script, if the file of idOfFile is a text file and the file content of idOfFile is -----BEGIN PRIVATE KEY-----.....----END PRIVATE KEY-n, for example, how about var privateKey = DriveApp.getFileById('idOfFile').getBlob().getDataAsString();? By the way, what is privatKeyFromCredents in your script?

– Tanaike
Mar 27 at 23:27





About the commented script, if the file of idOfFile is a text file and the file content of idOfFile is -----BEGIN PRIVATE KEY-----.....----END PRIVATE KEY-n, for example, how about var privateKey = DriveApp.getFileById('idOfFile').getBlob().getDataAsString();? By the way, what is privatKeyFromCredents in your script?

– Tanaike
Mar 27 at 23:27













I tried it also to store the key in a text files (in various formats). but that also did not worked. the following code was another try to convert the key that was stored in a txt file on drive, creat than a blob and transform the key to another charset: var privateKey = Utilities.newBlob(privatKeyFromCredents).getDataAsString() but that also failed...

– Jochen
Mar 28 at 13:08






I tried it also to store the key in a text files (in various formats). but that also did not worked. the following code was another try to convert the key that was stored in a txt file on drive, creat than a blob and transform the key to another charset: var privateKey = Utilities.newBlob(privatKeyFromCredents).getDataAsString() but that also failed...

– Jochen
Mar 28 at 13:08














I am wonderin in what format is a hard coded string is stored in an apps script file? because the length of the key string is different if check the length of the variable where the hard coded key is stored compared to read the key in utf-8 form a google doc or text file...

– Jochen
Mar 28 at 13:14





I am wonderin in what format is a hard coded string is stored in an apps script file? because the length of the key string is different if check the length of the variable where the hard coded key is stored compared to read the key in utf-8 form a google doc or text file...

– Jochen
Mar 28 at 13:14













@Jochen Thank you for replying. At first, I apologize my comment was not useful for your situation. As a next method, for example, how about directly upload the downloaded file when the service account is created to Google Drive, and use it? The file is json file. So the private key can be retrieved. Can I ask you about this?

– Tanaike
Mar 28 at 22:35





@Jochen Thank you for replying. At first, I apologize my comment was not useful for your situation. As a next method, for example, how about directly upload the downloaded file when the service account is created to Google Drive, and use it? The file is json file. So the private key can be retrieved. Can I ask you about this?

– Tanaike
Mar 28 at 22:35












1 Answer
1






active

oldest

votes


















0














// get Credentials form Drive in JSON format
var fileContent = DriveApp.getFileById('18t9NnzwKMlmQAnRUa_KovWdDvhk60oZT').getBlob().getDataAsString("UTF-8");

var serviceCredentials = JSON.parse(fileContent);
serviceCredentials['service_name'] = "Service Account Name";
serviceCredentials['scope'] = "https://www.googleapis.com/auth/script.external_request https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/datastore ";

var service = OAuth2.createService(serviceCredentials.service_name)
.setTokenUrl(serviceCredentials.token_uri)
.setPrivateKey(serviceCredentials.private_key)
.setIssuer(serviceCredentials.client_email)
.setPropertyStore(PropertiesService.getUserProperties())
.setCache(CacheService.getUserCache())
.setParam('access_type', 'offline')
.setScope(serviceCredentials.scope);

// for testing if access oauth setup is working or not
var access = service.hasAccess();
Logger.log('Access: ' + access); //true or false





share|improve this answer

























  • Code only answers are not exactly great. You should provide some explanatory text that summarizes why your answer works.

    – tehhowch
    Apr 1 at 13:45










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55377072%2fgoogle-apps-script-oauth2-library-error-for-service-accounts-if-private-key-is-n%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














// get Credentials form Drive in JSON format
var fileContent = DriveApp.getFileById('18t9NnzwKMlmQAnRUa_KovWdDvhk60oZT').getBlob().getDataAsString("UTF-8");

var serviceCredentials = JSON.parse(fileContent);
serviceCredentials['service_name'] = "Service Account Name";
serviceCredentials['scope'] = "https://www.googleapis.com/auth/script.external_request https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/datastore ";

var service = OAuth2.createService(serviceCredentials.service_name)
.setTokenUrl(serviceCredentials.token_uri)
.setPrivateKey(serviceCredentials.private_key)
.setIssuer(serviceCredentials.client_email)
.setPropertyStore(PropertiesService.getUserProperties())
.setCache(CacheService.getUserCache())
.setParam('access_type', 'offline')
.setScope(serviceCredentials.scope);

// for testing if access oauth setup is working or not
var access = service.hasAccess();
Logger.log('Access: ' + access); //true or false





share|improve this answer

























  • Code only answers are not exactly great. You should provide some explanatory text that summarizes why your answer works.

    – tehhowch
    Apr 1 at 13:45















0














// get Credentials form Drive in JSON format
var fileContent = DriveApp.getFileById('18t9NnzwKMlmQAnRUa_KovWdDvhk60oZT').getBlob().getDataAsString("UTF-8");

var serviceCredentials = JSON.parse(fileContent);
serviceCredentials['service_name'] = "Service Account Name";
serviceCredentials['scope'] = "https://www.googleapis.com/auth/script.external_request https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/datastore ";

var service = OAuth2.createService(serviceCredentials.service_name)
.setTokenUrl(serviceCredentials.token_uri)
.setPrivateKey(serviceCredentials.private_key)
.setIssuer(serviceCredentials.client_email)
.setPropertyStore(PropertiesService.getUserProperties())
.setCache(CacheService.getUserCache())
.setParam('access_type', 'offline')
.setScope(serviceCredentials.scope);

// for testing if access oauth setup is working or not
var access = service.hasAccess();
Logger.log('Access: ' + access); //true or false





share|improve this answer

























  • Code only answers are not exactly great. You should provide some explanatory text that summarizes why your answer works.

    – tehhowch
    Apr 1 at 13:45













0












0








0







// get Credentials form Drive in JSON format
var fileContent = DriveApp.getFileById('18t9NnzwKMlmQAnRUa_KovWdDvhk60oZT').getBlob().getDataAsString("UTF-8");

var serviceCredentials = JSON.parse(fileContent);
serviceCredentials['service_name'] = "Service Account Name";
serviceCredentials['scope'] = "https://www.googleapis.com/auth/script.external_request https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/datastore ";

var service = OAuth2.createService(serviceCredentials.service_name)
.setTokenUrl(serviceCredentials.token_uri)
.setPrivateKey(serviceCredentials.private_key)
.setIssuer(serviceCredentials.client_email)
.setPropertyStore(PropertiesService.getUserProperties())
.setCache(CacheService.getUserCache())
.setParam('access_type', 'offline')
.setScope(serviceCredentials.scope);

// for testing if access oauth setup is working or not
var access = service.hasAccess();
Logger.log('Access: ' + access); //true or false





share|improve this answer













// get Credentials form Drive in JSON format
var fileContent = DriveApp.getFileById('18t9NnzwKMlmQAnRUa_KovWdDvhk60oZT').getBlob().getDataAsString("UTF-8");

var serviceCredentials = JSON.parse(fileContent);
serviceCredentials['service_name'] = "Service Account Name";
serviceCredentials['scope'] = "https://www.googleapis.com/auth/script.external_request https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/datastore ";

var service = OAuth2.createService(serviceCredentials.service_name)
.setTokenUrl(serviceCredentials.token_uri)
.setPrivateKey(serviceCredentials.private_key)
.setIssuer(serviceCredentials.client_email)
.setPropertyStore(PropertiesService.getUserProperties())
.setCache(CacheService.getUserCache())
.setParam('access_type', 'offline')
.setScope(serviceCredentials.scope);

// for testing if access oauth setup is working or not
var access = service.hasAccess();
Logger.log('Access: ' + access); //true or false






share|improve this answer












share|improve this answer



share|improve this answer










answered Apr 1 at 13:42









Jochen Jochen

112 bronze badges




112 bronze badges















  • Code only answers are not exactly great. You should provide some explanatory text that summarizes why your answer works.

    – tehhowch
    Apr 1 at 13:45

















  • Code only answers are not exactly great. You should provide some explanatory text that summarizes why your answer works.

    – tehhowch
    Apr 1 at 13:45
















Code only answers are not exactly great. You should provide some explanatory text that summarizes why your answer works.

– tehhowch
Apr 1 at 13:45





Code only answers are not exactly great. You should provide some explanatory text that summarizes why your answer works.

– tehhowch
Apr 1 at 13:45








Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55377072%2fgoogle-apps-script-oauth2-library-error-for-service-accounts-if-private-key-is-n%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript