I can't make a basic http authentication using PHP - php

I have a work to do and I need to login to the webpage, and extract content from it.
The query has to be made of a username and an access key.
The problem is that I don't really know how to make a query with thos 2 elements, and in PHP.
So, I have found this code have this code :
$ak = "accesskey";
$username = 'admin';
$password = '123';
$remote_url = 'http://192.168.1.78/index.php';
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header' => "Authorization: Basic " . base64_encode("$username:$ak")
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents($remote_url, false, $context);
print($file);
But the output is simply the Webpage code, from the <!DOCTYPE html><html> to </html>
According to the webpage REST API, the result that I need to get is this :
{
success: true,
result: json_result
}
Any idea why it doesn't work ?
PS : here is the API documentation : https://www.vtiger.com/docs/rest-api-for-vtiger#/Authentication

The vTiger API (in 7.2 at least) has an odd combination of parameter and form POST payloads. Here is the Python script I used to get started. Note that it uses param in the getchallenge hit but data in the login hit:
import requests
from hashlib import md5
import urllib3
urllib3.disable_warnings() # shut up whining about that security stuff
encoding = 'ascii'
userName = 'Michael'
userToken = (access key from my preferences page)
APIURL='https://our.crm.instance/webservice.php'
session = requests.Session()
def getSession(session, name, token):
response = session.get(APIURL, params={'operation':'getchallenge', 'username':userName}, verify=False)
token_key = response.json()['result']['token']
combined = token_key + userToken
accessKey = md5(combined.encode(encoding)).hexdigest()
response1 = session.post(APIURL,
data={'operation':'login', 'username':userName, 'accessKey':accessKey},
verify=False)
return response1.json()['result']['sessionName']
sessionToken = getSession(session, userName, userToken)
types = session.get(APIURL, params={'operation':'listtypes', 'sessionName':sessionToken})
print(types.json())

Related

PHP to Python3 HMAC signature not resulting in the same signature

I have been trying to convert a php script to a python3 script and have been failing to send through a successful signature after troubleshooting through the issue.
The below PHP example code successfully goes through so I've copied the sent timestamp and signature to try and replicate it in my python3 code.
PHP Code
<?
$nonce = "2015-10-26 04:53:49 EDT";
$secret = "mkdaklmdflfkdsmaflkdmsfdkasmfdsmflks";
$req = array();
$req['t'] = $nonce;
$req['secret'] = $secret;
$post_data = json_encode($req);
$post_data = bin2hex($post_data);
$sign = hash_hmac("sha256", $post_data, $secret);
print($sign);
?>
Python 3 Code
import json
import hmac
import binascii
import hashlib
nonce = "2015-10-26 04:53:49 EDT"
secret = "mkdaklmdflfkdsmaflkdmsfdkasmfdsmflks"
payload = {}
payload["t"] = nonce
payload["secret"] = secret
payload_json = json.dumps(payload)
post_data = binascii.b2a_hex(payload_json.encode('utf-8'))
sign = hmac.new(bytes(secret, "utf-8"), post_data, hashlib.sha256).hexdigest()
print(sign)
Based on the successful request using PHP my signature should be:
'c30ddc5878ff7b1a9b1c9078ccbdc38afef25ed510681a3d3bfc56f6c9e2f26a'
Instead I'm getting:
'f9fc8749389137252e7f207468d88a5c871110403ec533496720efd715541ec2'
Any help troubleshooting this issue would be greatly appreciated as I'm new to Python.
Your problem is that by default, Python inserts spaces into the JSON string. Output of the PHP json_encode($req):
{"t":"2015-10-26 04:53:49 EDT","secret":"mkdaklmdflfkdsmaflkdmsfdkasmfdsmflks"}
Output of the Python json.dumps(payload):
{"t": "2015-10-26 04:53:49 EDT", "secret": "mkdaklmdflfkdsmaflkdmsfdkasmfdsmflks"}
You can fix this by specifying separators, i.e.:
json.dumps(payload, separators=(',', ':'))
Also, you can control the order of the elements by using OrderedDict instead of a plain dictionary:
from collections import OrderedDict
payload = OrderedDict()

android: get string with correct encoding from web service

I am trying get string result from PHP webservice in my android application, I used ksaop2 library and this is my code :
env = new SoapSerializationEnvelope(SoapEnvelope.VER11);
env.dotNet = false;
env.xsd = SoapSerializationEnvelope.XSD;
env.enc = SoapSerializationEnvelope.ENC;
request = new SoapObject("customWebService","addProductToCart");
request.addProperty("sessionID", sessionId);
request.addProperty("cartID", cartID);
request.addProperty("productID", productID);
request.addProperty("qty", qty);
request.addProperty("sku", productSKU);
env.setOutputSoapObject(request);
androidHttpTransport = new HttpTransportSE(
"http://mysiteeee.com/WebServiceSOAP/server.php?wsdl/",
60000);
androidHttpTransport.debug = true;
androidHttpTransport.call("", env);
result = env.getResponse();
It`s returned this:
???·???§?? ?¯?²?????? (???§??) ?§???²?§???? ???­?µ???? ?±?§ ???´?®?µ ?©?????¯.
I tested it on Chrome and Firefox with UTF-8 encoding and shows result correctly on browser.
How can I get result from web service with correct encoding and show it on android?
Try getting response this way :
androidHttpTransport.call(SOAP_ACTION, envelope);
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject)envelope.bodyIn;
String Test1 = result.getProperty(0).toString();
Edit : Try setting Xml header Tag for request :
androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

Signing errors from Withings Rest API

all
I have an app that is successfully getting authorized using Withing's api and OAuth.
I get the auth page from whitings, and I get the resulting token and verifier, however I can not make requests with those - I keep getting a 342 error: The signature (using Oauth) is invalid.
Code:
<?
require("include.php");
require_once("OAuth.php");
$domain = "oauth.withings.com";
$base = "/account/";
$base_url = "https://$domain$base";
$hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
$consumer = new OAuthConsumer("my key goes here :-)", "my key goes here :-)", "http://oauth.corp.withings.com/test.php");
$sig_method = $hmac_method;
$username="mydbusername";
$mySQL=" select * from `healthtokens` where service='WITHINGS' and userid='".$username."'";
$data=mysql_query($mySQL) or die("Died at 2<BR>".mysql_error());
$tokenrow = mysql_fetch_array( $data );
$serviceuserid=$tokenrow['serviceuserid'];
$otoken=$tokenrow['otoken'];
$overifier=$tokenrow['overifier'];
$acc_tok = new OAuthToken($otoken,$overifier);
$req = OAuthRequest::from_consumer_and_token($consumer, $acc_tok, "GET", "http://wbsapi.withings.net/user?action=getbyuserid&userid=".$serviceuserid);
$req->sign_request($sig_method, $consumer, $acc_tok);
$response = file_get_contents($req);
echo $response;
?>
Withings API docs: http://www.withings.com/en/api
An example of my call:
http://wbsapi.withings.net/user?action=getbyuserid&oauth_consumer_key=mybigconsumerkeyishere&oauth_nonce=f57a956d52c7412326fb0577e87addc4&oauth_signature=jiBNvql5r06HysjjVyxCh7C7ZUk%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1381758029&oauth_token=4088d6173b78b71cfd6ddd4245496de4b1f7b3c45bfb49f8e59b1202ccfc&oauth_version=1.0&userid=1234567
I know it sounds silly and it gave me some headaches too, but the "funny" thing with oauth 1 (or at least withings) is, that the order of the parameters is important.
Try using the EXACT order as in the withings oauth sample (http://www.withings.com/en/api/oauthguide):
http://wbsapi.withings.net/measure?
action=getmeas
&oauth_consumer_key=c331c571585e7c518c78656f41582e96fc1c2b926cf77648223dd76424b52b
&oauth_nonce=accbac1b7ee2b86b828e6dc4a5a539b2
&oauth_signature=XfobZMboIg2cRyNKAvyzONHHnKM%3D
&oauth_signature_method=HMAC-SHA1
&oauth_timestamp=1311842514
&oauth_token=887557411788d5120537c6550fbf2df68921f8dd6f8c7e7f9b441941eb10
&oauth_version=1.0
&userid=831

login with curl and get session

hello i need somehow to get top Regional interest and interest over time from
http://www.google.com/trends?q=lingerie+&ctab=0&geo=id&date=all&sort=0
or better
http://www.google.com/insights/search/#q=lingerie&geo=ID&cmpt=q
so i found out that we have to login to export data can anybody give me an example doing this with our google username and password? maybe using curl to export the data? or something else
Thanks for looking in
Adam Ramadhan
Just to be quick about it, I used my xhttp class which is a curl wrapper, and I think the code is easy enough to follow.
<?php
header('content-type: text/plain');
// Set account login info
$data['post'] = array(
'accountType' => 'HOSTED_OR_GOOGLE', // indicates a Google account
'Email' => '', // full email address
'Passwd' => '',
'service' => 'trendspro', // Name of the Google service
'source' => 'codecri.me-example-1.0' // Application's name, e.g. companyName-applicationName-versionID
);
$response = xhttp::fetch('https://www.google.com/accounts/ClientLogin', $data);
// Test if unsuccessful
if(!$response['successful']) {
echo 'response: '; print_r($response);
die();
}
// Extract SID
preg_match('/SID=(.+)/', $response['body'], $matches);
$sid = $matches[1];
// Erase POST variables used on the previous xhttp call
$data = array();
// Set the SID in cookies
$data['cookies'] = array(
'SID' => $sid
);
$response = xhttp::fetch('http://www.google.com/insights/search/overviewReport?q=lingerie&geo=ID&cmpt=q&content=1&export=1', $data);
// CSV data in the response body
echo $response['body'];
?>
The result is at: http://codecri.me/apps/test/test.google.trends.php
But I'm not sure if the result is what you are looking for.
Since April 2012 Google changed it's auth policy, edit the Arvin's code as follows:
// Extract Auth
preg_match('/Auth=(.+)/', $response['body'], $matches);
$auth = $matches[1];
// Erase POST variables used on the previous xhttp call
$data = array();
// Set the Authorization header
$data['headers'] = array(
'Authorization' => 'GoogleLogin auth='.$auth
);
The curl man page describes how to provide username and password. Have you tried the -u flag?
-u/--user
Specify the user name and password to use for server authentication. Overrides -n/--netrc and --netrc-optional.
If you just give the user name (without entering a colon) curl will prompt for a password.
If you use an SSPI-enabled curl binary and do NTLM authentication, you can force curl to pick up the user name and password from your environment by simply specifying a single colon with this option: "-u :".
If this option is used several times, the last one will be used.

Automating Linkedin oAuth usin Curl and PHP

I am trying to automate the process of authenticating LinkedIn login in order to perform a public search for people on LinkedIn.
First i will try to explain what i was doing.
I am using four files:
oAuth.php (required)
linkedin.php (php LinkedIn library)
auth.php (which gets oAuth token from the LinkedIn lib file)
callback url demo.php?params (which, after successful authenticaton, prints the current user's profile and the search results using params)
The authentication url is https://api.linkedin.com/uas/oauth/authorize?oauth_token=$oauthtoken.
I did two things, neither seems to work; they are:
I am using curl to automate the process of going to the authentication url, posting fields (username, password, oauth token, csrfToken, duration, sourceAlias, etc., which I came to know from Firebug).
The only two things which change here are oauth token and csrfToken (by parsing the content in the authentication url). I was able to get both, each time the page loads, and finally trying to print the GET response from curl_exec.
Trying to post just the email and password, and trying to print a GET response.
For reference here is my auth.php:
function extract_unit($string, $start, $end)
{
$pos = stripos($string, $start);
$str = substr($string, $pos);
$str_two = substr($str, strlen($start));
$second_pos = stripos($str_two, $end);
$str_three = substr($str_two, 0, $second_pos);
$unit = trim($str_three); // remove whitespaces
return $unit;
}
session_start();
$config['base_url'] = 'http://linkedin.tweetrank.tk/auth.php';
$config['callback_url'] = 'http://linkedin.tweetrank.tk/demo.php';
$config['linkedin_access'] = 'my key';
$config['linkedin_secret'] = 'my secret';
include_once "linkedin.php";
# First step is to initialize with the consumer key and secret. We'll use
# an out-of-band oauth_callback
$linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['callback_url']);
//$linkedin->debug = true;
# Now we retrieve a request token. It will be set as $linkedin->request_token
$linkedin->getRequestToken();
$_SESSION['requestToken'] = serialize($linkedin->request_token);
# With a request token in hand, we can generate an authorization URL, which
# we'll direct the user to
//echo "Authorization URL: " . $linkedin->generateAuthorizeUrl() . "\n\n";
echo $url = $linkedin->generateAuthorizeUrl();
$token = $linkedin->generateAuthorizeToken();
//echo '<br><br>';
$data = file_get_contents($url);
$csrfToken = extract_unit($data,'name="csrfToken" value="','"');
//echo $csrfToken;
//echo $token;
//echo 'https://www.linkedin.com/uas/oauth/authenticate?oauth_token='.$token.'&trk=uas-continue';
// INIT CURL
$postParams = 'email=myemail&password=mypassword&duration=720&authorize=Ok%2C+I%27ll+Allow+It&extra=&access=-3&agree=true&oauth_token='.$token.'&appId=&csrfToken='.$csrfToken.'&sourceAlias=0_8L1usXMS_e_-SfuxXa1idxJ207ESR8hAXKfus4aDeAk';
Now I used the authentication URL and the postParams with curl.
In order to get login process through, one has to use linkedIn web page authorization step; No way we can have third party app accepting credentials and making linkedIn authorization with the link https://api.linkedin.com/uas/oauth/authorize?oauth_token=$oauthtoken
I think I understand what you are asking and the answer is no you cannot do that with LinkedIn. I have been facing similar problem recently and wasn't able to solve it. I guess the LinkedIn guys have a good point about data protecting and stuff.
Check this out:
http://developer.linkedin.com/message/6460
http://getsatisfaction.com/linkedin/topics/cant_use_linkedin_api_to_view_public_profiles_without_oauth_login

Categories