Connecting to OpenID using PHP cURL Showing Error - php

I am using the following code to request a token from a IdentityServer, which uses OpenID protocol:
$curl = curl_init( 'https://remoteserver.com/connect/token' );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1);
$code = $_GET['code']; // The code from the previous request
$redirect_uri = 'http://mycalldomain.com/test.php';
curl_setopt( $curl, CURLOPT_POSTFIELDS, array(
'redirect_uri' => $redirect_uri,
'grant_type' => 'authorization_code'
) );
curl_setopt( $curl, CURLOPT_USERPWD,
"MYCLIENTID" . ":" .
"MYCLIENTSECRET");
$auth = curl_exec( $curl );
print '$auth = ';print_r($auth); // to see the error
$secret = json_decode($auth);
$access_key = $secret->access_token;
Is outputing the following error:
$auth = {"ErrorMessage":"Unsupported Mediatype"}
Can someone guide on this please?

You should provide a Content-Type HTTP header that the resource you're POSTing things accepts, by adding something like this:
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
That will make it JSON (as an example!), and your output data (CURLOPT_POSTFIELDS) must correspond to the Content-Type you choose.
Currently, the Content-Type is "multipart/form-data", as per the PHP documentation:
If value is an array, the Content-Type header will be set to multipart/form-data.
If you want to use the Content-Type "application/x-www-form-urlencoded", then in addition to setting that as the Content-Type, you have to give CURLOPT_POSTFIELDS in that format too. Being a web development language, PHP has a built-in function http_build_query for encoding arrays in that format:
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query(array(
'redirect_uri' => $redirect_uri,
'grant_type' => 'authorization_code'
)));

Related

PHP CURL REST API Login successful. Please use XSRF-TOKEN and SESSIONID cookies along with x-xsrf-token header in future requests

I'm stuck on a basic API setup. I'm trying to test this API, using PHP CURL
https://inland.zethconapp.com/test/api/docs/
The Authentication Endpoints work just fine, with a 200 response.
$url = "https://inland.zethconapp.com/test/api/login";
$data = array (
"username" => "USER",
"password" => "PASS"
);
$ch = curl_init( $url );
$payload = json_encode( $data );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
$result = curl_exec($ch);
curl_close($ch);
The very limited docs show:
200 - Login successful. Please use XSRF-TOKEN and SESSIONID cookies along with x-xsrf-token header in future requests.
The next call is where I'm stuck, I'm trying the endpoint /inventory/by-customer
$url = "https://inland.zethconapp.com/test/api/inventory/by-customer";
$headers = array (
"Content-Type" => "application/json"
);
$data = array (
"custid" => "DURONT",
"facility" => "B01"
);
$ch = curl_init( $url );
$payload = json_encode( $data );
$headers = json_encode( $headers );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
curl_close($ch);
This results in 401:
{"error":{"message":"invalid csrf token","type":"general","errorCode":"1d21867f3fc04bd7","statusCode":401,"requestId":"d7cf0a72-80dc-4ea2-ae5b-11fe27c082c6"}}
401 - Unauthorized. The client has not authenticated or is missing the authentication token.
I've been messing around with these calls, and I do see the Login header response does give the token info, such as this:
XSRF-TOKEN=76368dc5c8e74d4da8a37cf00c66069829762c52f27f3a12342809ea1b3399ba; SESSIONID=ey
x-xsrf-token: 76368dc5c8e74d4da8a37cf00c66069829762c52f27f3a12342809ea1b3399ba
I do not know how to get this information into the next call.
Thank you all for your help.
UPDATE after the first comments.
Okay, I get this in the login header response:
[set-cookie] => XSRF-TOKEN=245fd2c5e5e5338f94b436cf6720e771174b1e7bb37065c9eeb010397c60499a;
Path=/
I isolated the actual token (245fd2c5e5e5338f94b436cf6720e771174b1e7bb37065c9eeb010397c60499a)
Then, following the instructions (Please use XSRF-TOKEN and SESSIONID cookies along with x-xsrf-token header in future requests.), I have this on the next call:
$url = "https://inland.zethconapp.com/test/api/inventory/by-customer";
$headers = array (
"Content-Type" => "application/json",
"x-xsrf-token"=>"".$csrf.""
);
$data = array (
"custid" => "GOLDDIST",
"facility" => "FRS"
);
$ch = curl_init( $url );
# Setup request to send json via POST.
$payload = json_encode( $data );
$headers = json_encode( $headers );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt($ch, CURLOPT_COOKIE, 'XSRF-TOKEN=$csrf; SESSIONID=$csrf');
# Return response instead of printing.
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
# Send request.
$result = curl_exec($ch);
curl_close($ch);
Still getting the error:
RESPONSE: {"error":{"message":"invalid csrf token","type":"general","errorCode":"1d21867f3fc04bd7","statusCode":401,"requestId":"b8b6b1d6-e8ac-4e46-b692-1e70cf4bf14d"}}
Does anything jump out?

Access web api using access token in MS Dynamics using php

For Previous question about Azure account, I can create an app using azure account.
Now I can get auth code from below url:
Auth_code
From Auth_code we can get the access token by:
$auth_code = $_GET['code'];
$result = access($auth_code);
function access($auth_code){
$redirectUri = 'https://XXXX /authorize.php';
$token_request_data = array (
"grant_type" => "authorization_code",
"code" => $auth_code,
"redirect_uri" => $redirectUri,
"client_id" => "client_id",
"client_secret" => "client_secret",
"resource" =>"resource" (From manifest in azure)
);
$token_request_body = http_build_query ( $token_request_data );
$curl = curl_init ( 'https://login.windows.net/common/oauth2/token' );
curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $curl, CURLOPT_POST, true );
curl_setopt ( $curl, CURLOPT_POSTFIELDS, $token_request_body );
curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER,false);
$response = curl_exec ( $curl );
$res = json_decode($response);
curl_close ( $curl );
Now I'm trying to access the web api using that access_token,I couldn't get the result.
For example:
$authHeader = 'Authorization:Bearer access_toke';
$ch = curl_init();
$url = 'https://domain/api/data/v8.0/contacts';
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_POST, false);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array($authHeader, 'Content- Type:application/json'));
$result = curl_exec($curl);
echo "<pre>";print_r($result);exit;
curl_close($curl);
I'm getting empty response. Now I have to know how to access the web API using access token.
When I try to run manually https://domain/api/data/v8.0/contacts, I can get all contacts in my crm.But when I try to access it by access_token using php,it returns empty.
Web api reference url : reference for web api url
Refer to the guide Compose HTTP requests and handle errors, as the requirements shown at HTTP headers section:
Every request should include the Accept header value of application/json, even when no response body is expected.
And there are supernumerary blank in your PHP script at curl_setopt($curl, CURLOPT_HTTPHEADER, array($authHeader, 'Content- Type:application/json'));
You can remove the blanks in Content-Type and try again.
By the way, you can leverage Fiddler to capture the requests from your PHP client. We you get the response body content and request status code via the tool. We can match the status code with the list at https://msdn.microsoft.com/en-us/library/gg334391.aspx#bkmk_statusCodes. If the code is always 200 without response body, you may check your code in web api.

oauth2 in php - specified in curl

I am trying to implement the authentication as specified here : https://api.thermosmart.com/apidoc/
I get through the first steps and get an authorization code back. I need to exchange that for an acces_token. The step in curl is specified as:
# 4. Exchange authorization code for Access token (read out the code from the previous response)
curl -k -u client123:client-secret -b cookie.txt -vd "grant_type=authorization_code&code=HPOfdlCbiZ1tI4Lv&redirect_uri=..." "url for token"
My code in PHP:
$curl = curl_init( 'url for token' );
curl_setopt( $curl, CURLOPT_POST, TRUE );
curl_setopt($curl, CURLOPT_COOKIEJAR, "cookie.txt");
$userpwd = $oauth2_client_id.":".$oauth2_secret;
curl_setopt($curl, CURLOPT_USERPWD, $userpwd);
curl_setopt( $curl, CURLOPT_POSTFIELDS, array(
'redirect_uri' => $oauth2_redirect,
'code' => $code, // The code from the previous request
'grant_type' => 'authorization_code'
) );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1);
$auth = curl_exec( $curl );
}
$secret = json_decode($auth);
$access_key = $secret->access_token;
echo "OAuth2 server provided access token: " . $access_key;
Any help on this will be much appreciated.
Have struggled with the same question (for Qt Quick application, but maybe it can help you)...
(Asking for help resulted in quick response from ThermoSmart...
My code to exchange access token for authorization code:
req.open("POST", "https://api.thermosmart.com/oauth2/token", true, client_id, client_secret);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send("grant_type=authorization_code"+"&code="+ authorization_code + "&redirect_uri=" + redirect_uri);

How can I get the registrationIDs from clients using php?

Who can tell me how can I get the "$registrationIDs = array( "reg id1","reg id2");", mentioned in the following code, which is posted here GCM with PHP (Google Cloud Messaging)
<?php
// Replace with real server API key from Google APIs
$apiKey = "your api key";
// Replace with real client registration IDs
$registrationIDs = array( "reg id1","reg id2");
// Message to be sent
$message = "hi Shailesh";
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message ),
);
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
//curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// curl_setopt($ch, CURLOPT_POST, true);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fields ));
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
echo $result;
//print_r($result);
//var_dump($result);
?>
You need to build a Web page that the app can use to communicate the RegID, once the app receives the RegID. You'll have to introduce some kind of server-side storage (a database, a file) that the RegID will be stored in.
Depending on your business, you might want to accept some additional parameters. POST form is a good place for those.
Then in the app, once you get the RegID, you perform a HTTP request, passing the RegID along. Word of caution: don't call HttpClient from the main thread. Use an AsyncTask, or spin a new Thread.

Sending notifications to Google Cloud Messaging with php gives me Unauthorized Error 401

Searching for some info about how to send notifications using GCM but with PHP instead of servlets, i found this: GCM with PHP (Google Cloud Messaging)
I tested the working code of the responses of these questions, also i created a Key for browser apps (with referers), and i give permissions to this ip: .mywebsite.com/ (te php file is on this url: "http://www.mywebsite.com/~jma/cHtml5/cap/kk.php")
But i'm getting this response: Unauthorized Error 401
What i'm doing wrong?
this is the php file:
<?php
// Replace with real server API key from Google APIs
$apiKey = "fictional key";
// Replace with real client registration IDs
$registrationIDs = array( "APA91asdasdSDGGS232S13S4213abGqiNhCIXKjlxrkUYe_xTgTacNGB5n16b380XDd8i_9HpKGRHkvm8DDet4_WK3zumjDEKkTRWLgPS7kO-BrKzWz7eWFQaDD9PJ8zA6hlSqL9_zH21P8K22ktGKmo_VIF6YAdU9ejJovrKBTpgQktYkBZBf9Zw","APAasdasd32423dADFG91bHYYxYB7bFiX5ltbJt6A-4MBiNg7l4RS4Bqf3jIfYviaaUfZ810XJo2o66DY9-jdeJk_JR8FIZCyrmCv-eu_WLkGZ8KaoHgEDR_16H2QPm98uHpe1MjKVXbzYc4J89WMmcIrl5tHhWQnIQNzaI6Zp6yyFUNUQ");
// Message to be sent
$message = "Test Notificación PHP";
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message ),
);
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
//curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch, CURLOPT_POST, true);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fields ));
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
echo $result;
//print_r($result);
//var_dump($result);
?>
Solved!!!
you must use Key for server apps (with IP locking) instead of browser key
:)
You need to use the key for server apps in the field of API key in your server side coding.
While creating the server key don't enter anything inside IP address field.

Categories