PHP Curl vs Python Requests - php

I am currently writing a piece of code to interface with an API in Python. Supplied by the company that hosts the API is a PHP script that logs into the API given the correct username and password, retrieved the current event ID (JSON format), and then logs out. This works perfectly.
Currently, I am in the process of writing a script in Python to do the very same thing, the current code is shown below. It logs in and out successfully, however, when it tries to retrieve the current event ID I get the status code 404, suggesting that the URL doesn't exist, despite this same URL working with the PHP code.
PHP Code:
define('BASE_URL', 'https://website.api.com/');
define('API_USER', 'username');
define('API_PASS', 'password');
$cookiefile = tempnam(__DIR__, "cookies");
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);
$loginParams = array(
'username' => API_USER,
'password' => API_PASS
);
$obj = CurlPost($ch, BASE_URL . '/api/login', $loginParams);
if( $obj->success )
{
echo 'API login successful.' . PHP_EOL;
}
$obj = CurlGet($ch, BASE_URL . '/api/current-event-id');
echo 'API current event ID: ' . $obj->currentEventId . PHP_EOL;
// logout of the API
$obj = CurlGet($ch, BASE_URL . '/api/logout' );
if( $obj->success )
{
echo 'Logged out successfully.' . PHP_EOL;
}
curl_close($ch);
exit(0);
// -------------------------------------------------------------------------
// Functions
// -------------------------------------------------------------------------
// Run cURL post and decode the returned JSON object.
function CurlPost($ch, $url, $params)
{
$query = http_build_query($params);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, count($query));
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
$output=curl_exec($ch);
$obj = json_decode($output);
return $obj;
}
// Run cURL get and decode the returned JSON object.
function CurlGet($ch, $url)
{
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, '');
$output=curl_exec($ch);
$obj = json_decode($output);
return $obj;
}
Python Code:
import requests
BASE_URL = 'https://website.api.com/';
API_USER = "username";
API_PASS = "password";
headers = {'content-type': 'application/json'}
PARAMS = {'username':API_USER,'password':API_PASS}
session = requests.Session()
# Login
resp = session.post(BASE_URL + '/api/login',data=PARAMS)
if resp.status_code != 200:
print("*** ERROR ***: Login failed.")
else:
print("API login successful.")
resp = session.get(BASE_URL + '/api/current-event-id', headers=headers)
print(resp.status_code)
print(resp.text)
# Logout
resp = session.get(BASE_URL + '/api/logout')
if resp.status_code != 200:
print("*** ERROR ***: Logout failed.")
else:
print("API logout successful.")

It's ideal to change BASE_URL to:
'https://website.api.com'
the code looks fine to me when compared to php and should normally work.(Shouldn't you be passing some kind of authentication like a token?).
try debugging your API using postman.

It turns out that my API will only accept cookies transferred in the header, so I wrote a slight hack that dumped the cookiejar into a string that could be sent in the header file.
cookies = json.dumps(requests.utils.dict_from_cookiejar(resp.cookies));
cookies = cookies.replace('"', '')
cookies = cookies.replace('{', '')
cookies = cookies.replace('}', '')
cookies = cookies.replace(': ', '=')
cookies = cookies.replace(',', ';')
headers = {'Cookie':cookies}
resp = session.get(BASE_URL + '/api/current-event-id', headers=headers)

Related

How to connect with 2ba it's API using PHP

Im trying to connect to the API services of 2ba. Somehow I just can't connect. I get the error: error: "invalid_client"
I dont know what to try, it feels like I need to hash my cliend_secret or complete url but I dont see that in the documentation.
This is my code (PHP):
<?php
// ---- GET TOKEN ----
// Base url for all api calls.
$baseURL = 'https://authorize.2ba.nl';
// Specified url endpoint. This comes after the baseUrl.
$endPoint = '/OAuth/Token';
// Parameters that are required or/and optianal for the endPoint its request.
$parameters = 'grant_type=password&username=abc#abc.com&password=123abc&client_id=myClientID&client_secret=myClientSecret';
// All parts together.
$url = $baseURL . $endPoint . '?' . $parameters;
//Init session for CURL.
$ch = curl_init();
// Options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
// Init headers for access to the binance API signed data.
$headers = array();
$headers[] = 'Content-type: application/x-www-form-urlencoded';
$headers[] = 'Content-Length: 0';
// Setting headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute request.
$data = curl_exec($ch);
// If there is an error. Show whats wrong.
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
// Ends the CURL session, frees all resources and deletes the curl (ch).
curl_close($ch);
$result = json_encode($data);
echo($data);
exit();
?>
The authentication is oauth2 and I want to use the "Password Grant" flow since I can login automaticly this way. Also I see in the example code in C# that they encode the url, something im not doing yet but did try. It did not work.
// Using $encodedUrl like this: curl_setopt($ch, CURLOPT_URL, $encodedUrl); but does not work.
$encodedUrl = urlencode($url);
Alright so I fixed it. I now got my access token and am able to recieve data from the API. This is what I did:
// ---- GET TOKEN - FLOW: USER PSW ----
// No changes
$baseURL = 'https://authorize.2ba.nl';
// No changes
$endPoint = '/OAuth/Token';
// $parameters is now an array.
$parameters = array(
'grant_type' => 'password',
'username' => 'myUsername',
'password' => 'myPassword',
'client_id' => 'myClientID',
'client_secret' => 'myClientSecret'
);
// Removed the $parameter part
$url = $baseURL . $endPoint;
//Init session for CURL.
$ch = curl_init();
// Init headers for access to the binance API signed data.
$headers = array();
$headers['Content-Type'] = "application/x-www-form-urlencoded";
// NOTE: http_build_query fixed it.
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters)); // Automaticly encodes parameters like client_secret and id.
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute request.
$data = curl_exec($ch);
// If there is an error. Show whats wrong.
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
// Ends the CURL session, frees all resources and deletes the curl (ch).
curl_close($ch);
$result = json_encode($data);
echo($data);
exit();

Litlle problem with integration API -> php

I have this code in python that do a request to the API of suap passing the values of dados_usuario, that I tested and is working, but I wanna write the same code in php and I dont getting it, all I got was the token with the follow code, so, anyone could help me with the second part using curl in php?
python code - https://imgur.com/a/LpZ7j4S
import requests
# Obtaining the user's token
url = 'https://suap.ifrn.edu.br/api/v2/autenticacao/token/'
#username and password are your data used to access SUAP
dados_usuario = {
'username': '',
'password': ''
}
requisicao = requests.post(url, data=dados_usuario)
if requisicao.status_code == requests.codes.ok:
token_autenticacao = requisicao.json().get('token')
print ('\n--- Token de Autenticação:\n {}\n\n'.format(token_autenticacao))
# Obtaining User Data.
url = 'https://suap.ifrn.edu.br/api/v2/minhas-informacoes/meus-dados/'
headers = {
'Authorization':'JWT {}'.format(token_autenticacao)
}
requisicao = requests.get(url, headers=headers)
if requisicao.status_code == requests.codes.ok:
retorno_json = requisicao.json()
print ('--- Dados do Usuário Logado:\n{}\n\n'.format(retorno_json))
php code - https://imgur.com/a/tkxb9Gm
<?php
$url = 'https://suap.ifrn.edu.br/api/v2/autenticacao/token/';
$user_data = [
'username' => '',
'password' => ''
];
$ch = curl_init();
//Getting the user token
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $user_data);
$result = curl_exec($ch);
//Token variable
$token = json_decode($result, true);
curl_close($ch);
echo $token["token"]."\n\n";
I need get the user date with php, until now I just have the token, and I need get it with curl.
I got the resolver with this code
$token = "token hide";
$ch = curl_init('https://suap.ifrn.edu.br/api/v2/minhas-informacoes/meus-dados/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: JWT ' . $token
));
$data = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

How can I get an Authentication Token for Microsoft Translator API?

I want to get an Authentication Token for the Microsoft Translator API. This is my code:
<?php
//1. initialize cURL
$ch = curl_init();
//2. set options
//Set to POST request
curl_setopt($ch, CURLOPT_POST,1);
// URL to send the request to
curl_setopt($ch, CURLOPT_URL, 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken');
//return instead of outputting directly
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//whether to include header in the output. here set to false
curl_setopt($ch, CURLOPT_HEADER, 0);
//pass my subscription key
curl_setopt($ch, CURLOPT_POSTFIELDS,array(Subscription-Key => '<my-key>'));
//CURLOPT_SSL_VERIFYPEER- Set to false to stop verifying certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//3. Execute the request and fetch the response. check for errors
$output = curl_exec($ch);
if ($output === FALSE) {
echo "cURL Error" . curl_error($ch);
}
//4. close and free up the curl handle
curl_close($ch);
//5. display raw output
print_r($output);
?>
it gives me the following error:
{ "statusCode": 401, "message": "Access denied due to missing subscription key. Make sure to include subscription key when making requests to an API." }
which could mean that the key is invalid according to the website below, but I ensured the key is valid on the same website.
http://docs.microsofttranslator.com/oauth-token.html
I did find some examples online on how to get the Authenticationtoken, but they are outdated.
How can I get the AuthenticationToken/achieve that microsoft recognises my key?
You're passing the subscription-key wrong -
The subscription key should passed in the header (Ocp-Apim-Subscription-Key) or as a querystring parameter in the URL ?Subscription-Key=
And you should use Key1 or Key2 generated by the Azure cognitive service dashboard.
FYI - M$ has made a token generator available for testing purposes, this should give you a clue which keys are used for which purpose:
http://docs.microsofttranslator.com/oauth-token.html
Here's a working PHP script which translates a string from EN to FR (it's based on an outdated WP plugin called Wp-Slug-Translate by BoLiQuan which I've modified for this purpose):
<?php
define("CLIENTID",'<client-name>'); // client name/id
define("CLIENTSECRET",'<client-key>'); // Put key1 or key 2 here
define("SOURCE","en");
define("TARGET","fr");
class WstHttpRequest
{
function curlRequest($url, $header = array(), $postData = ''){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if(!empty($header)){
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
if(!empty($postData)){
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($postData) ? http_build_query($postData) : $postData);
}
$curlResponse = curl_exec($ch);
curl_close($ch);
return $curlResponse;
}
}
class WstMicrosoftTranslator extends WstHttpRequest
{
private $_clientID = CLIENTID;
private $_clientSecret = CLIENTSECRET;
private $_fromLanguage = SOURCE;
private $_toLanguage = TARGET;
private $_grantType = "client_credentials";
private $_scopeUrl = "http://api.microsofttranslator.com";
private $_authUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
// added subscription-key
private function _getTokens(){
try{
$header = array('Ocp-Apim-Subscription-Key: '.$this->_clientSecret);
$postData = array(
'grant_type' => $this->_grantType,
'scope' => $this->_scopeUrl,
'client_id' => $this->_clientID,
'client_secret' => $this->_clientSecret
);
$response = $this->curlRequest($this->_authUrl, $header, $postData);
if (!empty($response))
return $response;
}
catch(Exception $e){
echo "Exception-" . $e->getMessage();
}
}
function translate($inputStr){
$params = "text=" . rawurlencode($inputStr) . "&from=" . $this->_fromLanguage . "&to=" . $this->_toLanguage;
$translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?$params";
$accessToken = $this->_getTokens();
$authHeader = "Authorization: Bearer " . $accessToken;
$header = array($authHeader, "Content-Type: text/xml");
$curlResponse = $this->curlRequest($translateUrl, $header);
$xmlObj = simplexml_load_string($curlResponse);
$translatedStr = '';
foreach((array)$xmlObj[0] as $val){
$translatedStr = $val;
}
return $translatedStr;
}
}
function bing_translator($string) {
$wst_microsoft= new WstMicrosoftTranslator();
return $wst_microsoft->translate($string);
}
echo bing_translator("How about translating this?");
?>
Add your key also in the URL.
curl_setopt($ch, CURLOPT_URL, 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken?Subscription-Key={your key}');
But leave it also in the CURLOPT_POSTFIELDS.

how to post the value in url using PHP

I am creating a web service. I have tried to write an URL but its throwing error. I am not getting where I am going wrong. I want to pass these variable values in url and depending on this i want to call the web service
<?php
if($_POST["occupation"] == '1'){
$occupation = 'Salaried';
}
else{
$occupation = 'Self+Employed';
}
$url = 'http://www.aaa.com/ajaxv2/getCompareResults.html?interestRateType='.$_POST["interestRateType"]'.&occupation='.$_POST["occupation"].'&offeringTypeId='.$_POST["offeringID"].'&city='.$_POST["city"].'&loanAmt='.$_POST["loanAmt"].'&age='.$_POST["age"];
echo $url;
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
$json = json_decode($result, true);
//print_r($json);
//echo $json['resultList']['interestRateMin'];
$json_array = $json['resultList'];
print_r($json_array);
?>
Try below code. You have syntax error before &occupation
$url = 'http://www.aaa.com/ajaxv2/getCompareResults.html?interestRateType='.$_POST["interestRateType"].'&occupation='.$_POST["occupation"].'&offeringTypeId='.$_POST["offeringID"].'&city='.$_POST["city"].'&loanAmt='.$_POST["loanAmt"].'&age='.$_POST["age"];
Copy this because there is some ' and . error
$url = 'http://www.aaa.com/ajaxv2/getCompareResults.html?
interestRateType='.$_POST["interestRateType"].'&
occupation='.$_POST["occupation"].'&
offeringTypeId='.$_POST["offeringID"].'&
city='.$_POST["city"].'&
loanAmt='.$_POST["loanAmt"].'&
age='.$_POST["age"];

HP ALM REST API login using PHP CURL

I'm new to REST and I'm trying to develop a web app that will connect with JIRA from one sid (already covered) and with HP's ALM from the other side.
what I'm attempting to accomplish right now is basic authentication to ALM with PHP but can't seem to progress.
here is my code:
$handle=curl_init('http://192.168.1.7:8081');
$headers = array(
'Accept: application/xml',
'Content-Type: application/xml',
'Authorization: Basic YWRtaW46MTIzNA==',
);
$username='admin';
$password='1234';
$url = 'http://192.168.1.7:8081/qcbin/authentication-point/login.jsp';
curl_setopt_array(
$handle,
array(
CURLOPT_URL=>'http://192.168.1.7:8081/qcbin/rest/domains/default/projects/Ticomsoft/defects?login-form-required=y',
//CURLOPT_COOKIEFILE=>$ckfile,
CURLOPT_POST=>true,
//CURLOPT_HTTPGET =>true,
CURLOPT_COOKIEJAR=>$ckfile,
CURLOPT_VERBOSE=>1,
//CURLOPT_POSTFIELDS=>,
//CURLOPT_GETFIELDS=>'j_username=admin&j_password=1234&redirect-url=http://192.168.1.7:8081/myUiResource.jsps',
CURLOPT_SSL_VERIFYHOST=> 0,
CURLOPT_SSL_VERIFYPEER=> 0,
CURLOPT_RETURNTRANSFER=>true,
CURLOPT_FOLLOWLOCATION=>true,
CURLOPT_HEADER=>false,
CURLOPT_HTTPHEADER=> $headers,
CURLOPT_AUTOREFERER=>true
//CURLOPT_COOKIE=>
//CURLOPT_USERPWD=>"admin:yahala"
//CURLOPT_CUSTOMREQUEST=>"POST"
)
);
$result=curl_exec($handle);
$ch_error = curl_error($handle);
$response = curl_getinfo($handle);
print_r($response);
if ($ch_error) {
echo "cURL Error: $ch_error";
} else {
//var_dump(json_decode($result, true));
echo $result;
}
curl_close($handle);
?>
as you can see there is a lot of garbage as my trial and error progressed.
Here we go. I followed the QC Rest API documentation to study the order that QC expects requests to be made. I've tested it against ALM11. I'm new to cURL as well, but this should get you in and working......
<?php
//create a new cURL resource
$qc = curl_init();
//create a cookie file
$ckfile = tempnam ("/tmp", "CURLCOOKIE");
//set URL and other appropriate options
curl_setopt($qc, CURLOPT_URL, "http://qualityCenter:8080/qcbin/rest/is-authenticated");
curl_setopt($qc, CURLOPT_HEADER, 0);
curl_setopt($qc, CURLOPT_HTTPGET, 1);
curl_setopt($qc, CURLOPT_RETURNTRANSFER, 1);
//grab the URL and pass it to the browser
$result = curl_exec($qc);
$response = curl_getinfo($qc);
//401 Not authenticated (as expected)
//We need to pass the Authorization: Basic headers to authenticate url with the
//Correct credentials.
//Store the returned cookfile into $ckfile
//Then use the cookie when we need it......
if($response[http_code] == '401')
{
$url = "http://qualityCenter:8080/qcbin/authentication-point/authenticate";
$credentials = "qc_username:qc_password";
$headers = array("GET /HTTP/1.1","Authorization: Basic ". base64_encode($credentials));
curl_setopt($qc, CURLOPT_URL, $url);
curl_setopt($qc, CURLOPT_HTTPGET,1); //Not sure we need these again as set above?
curl_setopt($qc, CURLOPT_HTTPHEADER, $headers);
//Set the cookie
curl_setopt($qc, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt($qc, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($qc);
$response = curl_getinfo($qc);
//The response will be 200
if($response[http_code] == '200')
{
//Use the cookie for subsequent calls...
curl_setopt($qc, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt($qc, CURLOPT_RETURNTRANSFER, true);
curl_setopt($qc, CURLOPT_URL, "http://qualityCenter:8080/qcbin/rest/domains/Your_Domain/projects/Your_Project/defects");
//In this example we are retrieving the xml so...
$xml = simplexml_load_string(curl_exec($qc));
print_r($xml);
//Call Logout
logout($qc,"http://qualityCenter:8080/qcbin/authentication-point/logout");
}
else
{
echo "Authentication failed";
}
}
else
{
echo "Not sure what happened?!";
}
//Close cURL resource, and free up system resources
curl_close($qc);
function logout($qc, $url)
{
curl_setopt($qc, CURLOPT_URL, $url);
curl_setopt($qc, CURLOPT_HEADER, 0);
curl_setopt($qc, CURLOPT_HTTPGET,1);
curl_setopt($qc, CURLOPT_RETURNTRANSFER, 1);
//grab the URL and pass it to the browser
$result = curl_exec($qc);
}
?>
Let me know if it worked!
Thanks,
Rich
one of the important things to keep in mind is after authenticating you must do the following
POST /qcbin/rest/site-session
with cookies LWSSO
this will return QCSession and XSRF-TOKEN which are needed to perform any operations
Here is my solution in Perl for this problem: The authentication step is performed first, setting the cookie for the next libcurl request which then can be performed with no problems. This is a version for background jobs. For a dialog application, the credentials could be passed through from the user's input instead. Also, I had to do this with https instead of http. The Perl program also shows how to instruct curl for https (there is a very good how-to on http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/ ).
#!/usr/bin/perl
# This script accesses, as a proxy, the REST API of the HP quality center
# Running it without query parameter, the complete list of defects is returned
# A query parameter, e.g. 'query={id[2283]}' will be passed as is to the HP QC API
# We are using the libcurl wrapper WWW::Curl::Easy
# The access is https, so a certificate has to be passed to libcurl
# The main point for using curl, however, is the authentication procedure:
# HP requires a preparative call to a special authentication service
# The authentication ticket will then be passed back as a cookie
# Only with this ticket, the real GET request on the defects can be performed
use WWW::Curl::Easy;
use strict;
use warnings;
use constant {
URL_QC_DEFECTS => "https://[QC DOMAIN]/qcbin/rest/domains/[DOMAIN]/projects/[PROJECT]/defects/",
URL_QC_AUTH => "https://[QC DOMAIN]/qcbin/authentication-point/authenticate",
PATH_CERT => "[PATH TO CREDENTIALS]" # contains certificate and credentials, see below
};
doRequest( URL_QC_DEFECTS . "?" . $ENV{QUERY_STRING} );
return 0;
sub doRequest {
my ($url,$cookies,$response) = (shift,"","");
eval {
my $curl = get_curl_instance(\$cookies,\$response);
authenticate( $curl );
get( $curl, $url );
if ($response =~ /.*?(<\?xml\b.*)/s) {
print "Content-Type:text/xml\n\n";
print $1;
}
else {
die "The response from HP QC is not in XML format";
}
};
if ($#) {
print "Content-Type:text/plain\n\n$#";
}
}
sub get_curl_instance {
my ($cookie,$response) = #_;
my $curl = WWW::Curl::Easy->new( );
open( my $cookiefile, ">", $cookie) or die "$!";
$curl->setopt( CURLOPT_COOKIEFILE, $cookiefile );
open( my $responsefile, ">", $response) or die "$!";
$curl->setopt( CURLOPT_WRITEDATA, $responsefile );
$curl->setopt( CURLOPT_SSL_VERIFYPEER, 1);
$curl->setopt( CURLOPT_SSL_VERIFYHOST, 2);
$curl->setopt( CURLOPT_CAINFO, cert() );
$curl->setopt( CURLOPT_FOLLOWLOCATION, 1 );
return $curl;
}
sub authenticate {
my $curl = shift;
my ($rc,$status);
$curl->setopt( CURLOPT_URL, URL_QC_AUTH );
$curl->setopt( CURLOPT_USERPWD, cred( ) );
if (($rc = $curl->perform( )) != 0) {
die "Error Code $rc in curl->perform( ) on URL " . URL_QC_AUTH;
}
if (($status=$curl->getinfo(CURLINFO_HTTP_CODE))!="200") {
die "HTTP-Statuscode $status from authentication call";
}
}
sub get {
my ($curl,$url) = #_;
my ($rc,$status);
$curl->setopt( CURLOPT_URL, $url );
$curl->setopt( CURLOPT_HEADER, { Accept => "text/xml" } );
if (($rc = $curl->perform( )) != 0) {
die "Error Code $rc from defects request";
}
if (($status=$curl->getinfo(CURLINFO_HTTP_CODE))!="200") {
die "HTTP Statuscode $status from defects request";
}
}
sub cred {
open CRED, PATH_CERT . '/.cred_qc' or die "Can't open credentials file: $!";
chomp( my $cred = <CRED>);
close CRED;
return $cred;
}
sub cert {
return PATH_CERT . '/qc.migros.net.crt';
}
As an alternative to Sohaib's answer concerning the need to POST to /qcbin/rest/site-session after authenticating, you can do both in one step by POSTing to /qcbin/api/authentication/sign-in , as per the below:
"There are four cookies that come back, and in ALM 12.53 the authentication point has changed ( but the documentation has not so it sends you to the wrong place ! )
So, send a POST request with BASIC authentication, base64 encoded username / password to /qcbin/api/authentication/sign-in and you will get back
LWSSO_COOKIE_KEY
QCSESSION
ALM_USER
XSRF_TOKEN
include these with all your subsequent GETS and PUTS and you should be OK."
(This answer is taken from https://community.microfocus.com/t5/ALM-QC-User-Discussions/Authentication-fails-when-trying-to-pull-data-from-ALM-server/td-p/940921, and worked for me in a similar context).

Categories