Unable to connect HP ALM API via google script - rest

I'm trying to call HPQC API to get some reports but I'm not able to get the QCsession cookie when I call /qcbin/rest/site-session. I successfully authenticated with /qcbin/authentication-point/authenticate but I'm stuck in the next phase.
Not that I can use the API without any trouble with Postman, but my Google script doesn't work.
Here's a look at the call I'm doing :
var headers = { "Accept":"application/xml",
"Content-Type":"application/xml",
"method": "POST",
"headers" : {"Authorization": digestfull },
"muteHttpExceptions": true
};
var resp = UrlFetchApp.fetch(url,headers);
var cookie = resp.getAllHeaders();//['Set-Cookie'];//.split(';')[0].toString();
Logger.log(cookie);
//Get session cookie
param = "/hp/rest/site-session";
var url2 = hpqc + param + api_key;
var payload = "<session-parameters><client-type>REST Client</client-type></session-parameters>";
var headers2 = { "Accept":"application/json",
"Content-Type":"application/xml",
"method": "POST",
"muteHttpExceptions" : true,
"cookie" : cookie,
"body" : payload
};
resp = UrlFetchApp.fetch(url2,headers2);
The first call works fine, but the second gives me the following response :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Error 401 Authentication failed. Browser based integrations - to login append '?login-form-required=y' to the url you tried to access.</title>
</head>
<body><h2>HTTP ERROR 401</h2>
<p>Problem accessing /qcbin/rest/site-session. Reason:
<pre> Authentication failed. Browser based integrations - to login append '?login-form-required=y' to the url you tried to access.</pre></p><hr><i><small>Powered by Jetty://</small></i><hr/>
It seems that the cookies aren't correctly sent.
Can you please help me find what is wrong with my code ? I'm sorry if it's too obvious, I'm learning to use google script.
Thank you

I changed the following code
var payload = "<session-parameters><client-type>REST Client</client-type></session-parameters>";
var headers2 = { "Accept":"application/json",
"Content-Type":"application/xml",
"method": "POST",
"muteHttpExceptions" : true,
"cookie" : cookie,
"body" : payload
};
with this and it worked
var payload = "<session-parameters><client-type>REST Client</client-type></session-parameters>";
var headers = {// "accept":"application/json",
//"contentType":"application/json",
"method": "POST",
"muteHttpExceptions" : true,
"headers" : {
"Content-type" : "application/xml",
"Accept" : "application/json",
"Cookie" : cookie
},
"payload" : payload
};
Thank you TheMaster for giving me the hint !!

Related

how to access specific team site in share-point using rest apis

goal: I'm trying to access a specific team site which created in my share-point account using REST APIs and create a folder inside there (Documents folder - default location)
actual results: I'm getting 403 error code. following is the response body which I'm getting.
{
"error": {
"code": "-2147024891, System.UnauthorizedAccessException",
"message": {
"lang": "en-US",
"value": "Access denied. You do not have permission to perform this action or access this resource."
}
}
}
expected result: specified folder should be created and response code should be 201 or 200
what I've tried:
first registered the app in both share-point as well as Azure
get the bearer token calling share-point rest api
tested get apis for share-point and all are worked as expected.
before each request I set the bearer token in the request header
following are the other request headers which I'm setting
Content-Type : application/json;odata=verbose
X-RequestDigest : some random string
Accept : application/json;odata=verbose
following is the share-point REST API, I used POST method for creating a folder
https://***.sharepoint.com/sites/TeamSite_ForB/_api/web/folders
following is the request body which I'm sending
{
"__metadata":{
"type":"SP.Folder"
},
"ServerRelativeUrl":"/Shared Documents/buddhika-test-folder-03"
}
In the share-point documentation site they've provided the API format.
I tried with that format , but couldn't get the result as well.
following is from share-point documentation.
To access a specific site, use the following construction:
http://server/site/_api/web
in that case I have tried as following
https://***.sharepoint.com/TeamSite_ForB/_api/web/folders
I'm getting response as 404 Not found with no response message.
I have searched through many documents but couldn't find how to access a specific team site.
Any help would be appreciated.
The request REST API URL as below.
https://***.sharepoint.com/sites/TeamSite_ForB/_api/web/folders
The request body as following.
{
"__metadata":{
"type":"SP.Folder"
},
"ServerRelativeUrl":"Shared Documents/buddhika-test-folder-03"
}
Example code:
<script src="//code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
function getFormDigest() {
return $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/contextinfo",
method: "POST",
headers: { "Accept": "application/json; odata=verbose" }
});
}
function createFolderTest() {
var documentLibraryName = "Shared Documents";
var folderName="buddhika-test-folder-03";
if(folderName!=""){
createfolder(documentLibraryName,folderName).done(function (data) {
console.log('Folder creted succesfully');
}).fail(function (error) {
console.log(JSON.stringify(error));
});
}
return true;
}
function createfolder(documentLibraryName,folderName){
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/folders";
return getFormDigest().then(function (data) {
return $.ajax({
url: requestUri,
type: "POST",
contentType: "application/json;odata=verbose",
data:JSON.stringify({'__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': documentLibraryName+'/'+folderName}),
headers: {
"accept":"application/json;odata=verbose",
"X-RequestDigest":data.d.GetContextWebInformation.FormDigestValue
}
});
});
}
</script>
<input type="button" onclick="createFolderTest()" value="Create Folder"/>

401 Auth error with apps script connecting to 3rd party API

I am beating my head up trying to get this to work.
Any assistance would be appreciated.
I have tested the auth in Insomnia and Postman and its working fine but not with apps script. I am getting a "401 Authorization Required" response.
function myFunction() {
var url = "https://api.tempo.io/core/3/worklogs/project/MYPROJECT";
var token = "THISISATOKEN";
var headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": "Bearer "+ token,
"muteHttpExceptions": true
};
var options = {
"method" : "get",
"headers" : headers
};
var response = UrlFetchApp.fetch(url,headers);
Logger.log(response);

Response with status: 0 for URL: null

I have a service that do post. The service is being hosted in another machine. When I tried to post using Postman, it works fine. Now, when I tried to post using my Angular2 app which is run in another machine I got an error "Response with status: 0 for URL: null." The code in my angular service is as follows:
postQuestions() {
var json = JSON.stringify({
"TestInfo_FK" : "612",
"Resource_FK" : 0,
"QuestionNo" : 22,
"ContentType" : "HTML",
"Content" : "This is the question from Jason",
"NoOptions" : 4,
"OptionLayout" : "Vertical",
"Answer" : "A"
});
var url = 'http://my.service.net/api/ONLINE/Question';
var params = 'json=' + json;
var headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
return this._http.post(url, params, {
headers: headers
})
.map(res => res.json());
}
how to solve this issue?
This situation arises when your hosted service is not able to be accessed via cross origin(CORS) .So if u you are accessing Spring Rest service then use #CrossOrigin annotation on service.
OR use
flask-restful to build remote API
from flask_restful.utils import cors
from flask_restful import Api
api = Api(app, decorators=[cors.crossdomain(origin='*')])
I found out what was causing the issue.. Its a server side issue. You need to set the CORS middleware first then the remaining API middlewares.
Please note i am working with Laravel 5.6 + Angular 5
Wrong Code
'api' => [
'throttle:60,1',
'bindings',
\Barryvdh\Cors\HandleCors::class,
],
Currect Code
'api' => [
\Barryvdh\Cors\HandleCors::class,
'throttle:60,1',
'bindings'
],

Twitter Oauth2 - Error in obtaining the bearer token

I have followed and double checked the steps to get a bearer token from https://dev.twitter.com/oauth/application-only
i keep getting the following error :
Status : 403 Forbidden
{"errors":[{"code":99,"message":"Unable to verify your credentials","label":"authenticity_token_error"}]}
I tried passing grant_type=client_credentials in body as well as query parameter.
The URL i am hitting is : https://api.twitter.com/oauth2/token?grant_type=client_credentials
Headers Set :
Authorization : Basic [base64encoded(client_key:client_secret)]
Content-Type : application/x-www-form-urlencoded;charset=UTF-8
I am using poster as the rest client to make the calls.
Could any one point out where i may be going wrong.
Thanks a lot.
Send "grant_type=client_credentials" as the payload.
var options = {
"method":"post",
"headers": {
"Authorization":"Basic " + Utilities.base64Encode(param),
"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"
},
"payload" : "grant_type=client_credentials"
};
var response = UrlFetchApp.fetch(TOKEN_URL,options);

UrlFetchApp Authentication failed Freshbooks

So I am trying to communicate with the freshbooks api by making the sample request detailed on the developers page of freshbooks (http://developers.freshbooks.com/). We are doing token-based authentication as opposed to using OAuth.
I have my code logging the responses to my requests in a spreadsheet. The responses it has been logging are as follows:
<?xml version="1.0" encoding="utf-8"?>
<response xmlns="http://www.freshbooks.com/api/" status="fail">
<error>Authentication failed.</error>
<code>20010</code>
</response>
I have been able to authenticate when using a curl command in console, but not when running the script. Below is the code I used. Left out the logging to spreadsheet part and our specific url and authToken:
// Sample function to call into an API using basic HTTP auth
function freshbooksTest () {
var url = ;
var authToken = ;
var unamepass =authToken+":X";
var digestfull = "Basic "+unamepass;
var payload = '<request method="system.current"></request>';
var options =
{
"method" : "post",
"muteHttpExceptions": true,
"headers" : {"Authorization": digestfull},
"payload" : payload
};
var response = UrlFetchApp.fetch(url, options);
var xml = response.getContentText();
}
I have checked out threads where people are having similar problems, but the solutions were either not applicable to my situation, or have already been tried. Any suggestions are welcome.
Not specifically familiar with UrlFetchApp, but if it doesn't do it for you, you'll need to Base64 encode digestfull before you send it in the header.
Looks like you need to base 64 encode your auth token. Code should look like this:
function freshbooksTest () {
var url = ;
var authToken = ;
var unamepass = authToken+":X";
var digestfull = "Basic "+ Utilities.base64Encode(unamepass);
var payload = '<request method="system.current"></request>';
var options =
{
"method" : "post",
"muteHttpExceptions": true,
"headers" : {"Authorization": digestfull},
"payload" : payload
};
var response = UrlFetchApp.fetch(url, options);
var xml = response.getContentText();
}