Why is Forge returning code 403 for Data Connector API This clientId is not authorized to perform the operation - autodesk

Why is Forge returning code 403 for Data Connector API This clientId is not authorized to perform the operation. The token call comes back correctly but I get 403 on the gethubs {"warnings":[{"Id":null,"HttpStatusCode":"403","ErrorCode":"BIM360DM_ERROR","Title":"Unable to get hubs from BIM360DM EMEA.","Detail":"You don't have permission to access this API","AboutLink":null,"Source":null,"meta":null}]}}
And getcon as well "{"detail":"This clientId is not authorized to perform the operation.","status":403,"type":"error","title":"Forbidden","id":69852363,"errors":[{"detail":"This clientId is not authorized to perform the operation.","title":"Forbidden","type":"error"}]}"
These are the calls from App script using, what I think is, 3-legged code grant.
function getToken() {
var formData = {
'client_id': 'ClientID',
'client_secret': 'ClientSecret',
'grant_type': 'client_credentials',
'scope': 'user-profile:read user:read user:write viewables:read
data:create data:read data:write data:search bucket:read bucket:create
bucket:update code:all account:read account:write',
'prompt':'login'
}; var response =
UrlFetchApp.fetch('https://developer.api.autodesk.com/authentication/v1/a uthenticate', {
method: 'POST',
payload: formData
});
var token = JSON.parse(response.getContentText());
console.log(token);
return token.access_token;
}
function getHubs() {
var token = getToken();
console.log(token);
var header = {"Authorization" : "Bearer " + token};
console.log(header);
var options = {
"method" : "get",
"headers" : header
};
var response = UrlFetchApp.fetch('https://developer.api.autodesk.com/project/v1/hubs', options);
var hubs = JSON.parse(response.getContentText());
console.log(JSON.stringify(hubs));
}
function getDConn() {
var token = getToken();
console.log(token);
var header = {"Authorization" : "Bearer " + token,"Content-Type": "application/json" };
console.log(header);
var options = {
"method" : "post",
"headers" : header,
"description": "AccountExtract",
"isActive": true,
"scheduleInterval": "ONE_TIME",
"reoccuringInterval": null,
"effectiveFrom": "2022-10-06T10:00:00.106Z",
"effectiveTo": "2022-10-06T10:00:00.106Z",
"serviceGroups": "locations",
"callbackUrl": null,
"sendEmail": true,
"projectId": null
};
//Google Account ID
var response = UrlFetchApp.fetch('https://developer.api.autodesk.com/data- connector/v1/accounts/ACCOUNTID/requests', options);
var hubs = JSON.parse(response.getContentText());
console.log(JSON.stringify(hubs));

Related

put works in postman but not google scripts

I am trying to push sheets data from a quiz to an api. The put works fine in postman but I can't seem to get it to work in google scripts.
Postman
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Authorization", "Basic bmljazpuaWNr");
myHeaders.append("Cookie", "FB_ResponseHeaders=%7b%22X-XSS-Protection%22%3a%7b%22Key%22%3a%221%3b+mode%3dblock%22%2c%22Value%22%3a%225C-58-58-82-DB-E9-4D-AD-BF-23-F8-5A-65-1E-EE-7B-96-94-7C-E6%22%7d%2c%22X-Content-Type-Options%22%3a%7b%22Key%22%3a%22nosniff%22%2c%22Value%22%3a%22E9-85-E8-2B-38-74-3B-AA-71-5A-41-1D-65-49-06-A7-FF-B3-D2-57%22%7d%2c%22Strict-Transport-Security%22%3a%7b%22Key%22%3a%22max-age%3d31536000%3b+includeSubDomains%22%2c%22Value%22%3a%221D-31-04-88-80-8A-6A-27-8E-2D-72-C5-32-98-74-A9-F8-E8-0C-E7%22%7d%7d; fbd_cooked=!/muNNuj9SlbMhC0PporV/qqu1cgGGvczJaMywTIzq+9GDRYedxCjdCU9X3WnSt1ijLXqndrZJ1DCTVw=");
var raw = JSON.stringify({
"fieldName": "SingleLineText5",
"fieldValue": "question1test"
});
var requestOptions = {
method: 'PUT',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
Google Scripts
// put em in a payload
var payload = {
"fieldName": "SingleLineText7",
"fieldValue": "question1googleSheet" }
var encodedAuth = Utilities.base64Encode("nick:nick");
var headers = [{"Authorization" : "Basic " + encodedAuth},{"Content-Type":"application/json"}];
var options = {
'method': 'PUT',
'body': JSON.stringify(payload),
'headers': headers,
'redirect': 'follow'
}
response = UrlFetchApp.fetch(url, options);
//log the response
Logger.log(JSON.stringify(response));
Am receiving
Exception: Attribute provided with invalid value: headers
If i remove the "Content-Type" I get no error but send no data just returns {}
According to the documentation you are using the wrong parameter. It should be:
const options = {
method : "PUT", // this was correct
payload: JSON.stringify(payload), // correct this
followRedirects : true, // correct this
headers: headers
}

Google Apps Script : API Error message "client_id is required"

I've created a variable to hold the client ID (CLIENT_ID) but I keep getting an error message saying that the client ID is required when running this function. Anyone have any idea of what I've done wrong here?
function getAuth() {
var authBasedUrl = 'https://test-api.service.hmrc.gov.uk/oauth/authorize';
var response = UrlFetchApp.fetch(authBasedUrl, {
headers: {
'Accept' : 'application/vnd.hmrc.1.0+json',
'response_type': 'code',
'client_id' : CLIENT_ID,
'scope' : 'hello',
'redirect_uri' : 'https://www.xxxxxxx.com/'
}});
var result = JSON.parse(response.getContentText());
Logger.log(JSON.stringify(result, null, 2));
}
Based on the docs you need to make a POST request. There is a blockqoute on the page that says:
Include the request parameters in the request body, not as request
headers.
EDIT:
function getAuth() {
var authBasedUrl = 'https://test-api.service.hmrc.gov.uk/oauth/token';
var options = {
headers: {
'Accept': 'application/vnd.hmrc.1.0+json',
"Content-Type": "application/json"
},
payload: JSON.stringify({
client_id: 'RgwU6hvdxxxxxxic6LwIt',
client_secret: '9e8c9yyyyyyyyyyc2fc2ed9126',
grant_type: 'client_credentials',
scope: 'hello'
})
}
var response = UrlFetchApp.fetch(authBasedUrl, options);
var result = JSON.parse(response.getContentText());
console.log(result);
}

LinkedIn API OAUTH returning "grant_type" error

I am pretty new to coding, but trying to write a simple script using LinkedIn's API that will pull an organizations follower count into google app script. Before I can even query the API, I have to authenticate using oath explained in the LinkedIn API here.
This function returns with an error response
function callLinkedAPI () {
var headers = {
"grant_type": "client_credentials",
"client_id": "78ciob33iuqepo",
"client_secret": "deCgAOhZaCrvweLs"
}
var url = `https://www.linkedin.com/oauth/v2/accessToken/`
var requestOptions = {
'method': "POST",
"headers": headers,
'contentType': 'application/x-www-form-urlencoded',
'muteHttpExceptions': true
};
var response = UrlFetchApp.fetch(url, requestOptions);
var json = response.getContentText();
var data = JSON.parse(json);
console.log(json)
}
When I try sending the headers through I get this error as a response
{"error":"invalid_request","error_description":"A required parameter \"grant_type\" is missing"}
grant_type, client_id, client_secret do not go in the header of the request. Instead, try to put them in the body of the POST request with the content type x-www-form-urlencoded as you already had in the headers of the code you posted.
For example:
fetch('https://www.linkedin.com/oauth/v2/accessToken/', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: new URLSearchParams({
grant_type: 'client_credentials',
client_id: '78ciob33iuqepo',
client_secret: 'deCgAOhZaCrvweLs'
})
})
.then(response => response.json())
.then(responseData => {
console.log(JSON.stringify(responseData))
})
Using Apps Script you should send the payload like so:
Example:
function callLinkedAPI() {
var payload = {
"grant_type": "client_credentials",
"client_id": "78ciob33iuqepo",
"client_secret": "deCgAOhZaCrvweLs"
}
var url = `https://www.linkedin.com/oauth/v2/accessToken/`
var requestOptions = {
'method': "POST",
'contentType': 'application/x-www-form-urlencoded',
'muteHttpExceptions': true,
"payload":payload
};
var response = UrlFetchApp.fetch(url, requestOptions);
var json = response.getContentText();
var data = JSON.parse(json);
console.log(json)
}

How to include aws cognito authentication in a google apps script?

From Google Sheet's App Script, we are trying to access our database using authentication via aws-cognito-identity. I am having trouble even getting started because I am not sure how to import modules because this is not a node.js environment. Does anybody have experience doing this and would not mind sharing it?
Thanks
This is how I got this to work:
var authEndpoint = "https://[put your auth domain here].amazoncognito.com/oauth2/token";
var authClientId = "[put your Cognito client ID here]";
var authSecret = "[put your Cognito auth secret string here]";
var authExpirationTime = undefined;
var authLatestToken = undefined;
function getAuthToken() {
// If last known token is still valid, use it.
if (authLatestToken && authExpirationTime && authExpirationTime < new Date().getTime()) {
return authLatestToken;
}
// Otherwise, request new token from AWS Cognito
var params = {
method: "POST",
followRedirects: true,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic " + Utilities.base64Encode(authClientId + ":" + authSecret)
},
payload: "grant_type=client_credentials"
};
var response = UrlFetchApp.fetch(authEndpoint, params);
// Verify response
if (response.getResponseCode() !== 200) {
throw new Error("Authentication failed: HTTP Response not OK.");
}
var data = JSON.parse(response.getContentText());
if (!data.access_token) {
throw new Error("Authentication failed: No token returned.");
}
// Set internal vars and return token
authLatestToken = data.access_token;
if (data.expires_in > 0) {
authExpirationTime = new Date().getTime() + data.expires_in * 1000;
}
return authLatestToken;
}
Then you can add an authorization header with this bearer to any requests that need to be authenticated, for example:
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + getAuthToken()
},

Discord API tells me: "401: Unauthorized" when i make a GET with Google-Scripts: "UrlFetchApp.fetch()"

I'm setting up a api connection. I want to get informations from discord api for my app.
So I implemented OAuth2 without any problems, I have my access token. Then I tried query some endpoints (/users/#me, /users/#me/guilds,...) but every time I get the same error.
I'm sending my authorization token in headers but it's still returning error 401.
I call the script with the generated url:
https://discordapp.com/api/oauth2/authorize?client_id=XYZ&redirect_uri=https%3A%2F%2Fscript.google.com%2Fmacros%2Fs%2FAKfycbyyt9-FiVv0zXOr8p8pMfojwEs2AXvBftVN1xdWeU3UQ1xgURD%2Fexec&response_type=code&scope=identify
Here is my "authentication code":
function doGet(e){
if(typeof e.parameter.code !== 'undefined') {
var code = e.parameter.code;
getAccessToken(code);
}
return ContentService.createTextOutput('someThink..');
}
function getAccessToken(code){
var API_TOKEN_URL = 'https://discordapp.com/api/oauth2/token'
var CLIENT_ID = 'XYZ'
var CLIENT_SECRET = 'XYZ'
var REDIRECT_URI = 'https://script.google.com/macros/s/AKfycbyyt9-FiVv0zXOr8p8pMfojwEs2AXvBftVN1xdWeU3UQ1xgURD/exec'
data = {
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': REDIRECT_URI,
'scope': 'identify'
}
header = {
'method' : 'post',
'Content-Type': 'application/x-www-form-urlencoded',
'payload' : data
}
var result = UrlFetchApp.fetch(API_TOKEN_URL, header);
if (result.getResponseCode() == 200) {
var params = JSON.parse(result.getContentText());
Logger.log(params.access_token); // all is fine
getUser(params.access_token, params.token_type)
}
}
And this code is my API request:
function getUser(accessToken, token_type){
var API_USERS_URL = 'https://discordapp.com/api/users/#me';
header2 = {
'method' : 'GET',
'Authorization': token_type + ' ' + accessToken,
// I tested all of them
// 'followRedirects' : true,
// 'muteHttpExceptions': true,
// 'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
}
var resultUsers = UrlFetchApp.fetch(API_USERS_URL, header2); // ERROR HERE !
if (resultUsers.getResponseCode() == 200) {
var paramsUser = JSON.parse(result.getContentText());
Logger.log(paramsUser);
}
}
I accept the connection with discord with the same SCOPES: identify.
I tried so hard but I don't succeed. Every time the same error:
{"code": 0, "message": "401: Unauthorized"}
You're sending the header as the params/options parameter to UrlFetchApp.fetch(). Send the header as the header parameter in options:
var resultUsers = UrlFetchApp.fetch(API_USERS_URL,{headers: header2});