I have installed the package recommended by firebase for php custom tokens which can be found here, https://firebase.google.com/docs/auth/admin/create-custom-tokens found under the heading Create custom tokens using the third-party JWT library.
I have installed the php-jwt advised.
I then created a service account found here and in the /apis/credentials I get similar details as below which I downloaded.
"private_key": "-----BEGIN PRIVATE KEY-----veryLongKey---END PRIVATE KEY-----\n",
"client_email": "randomemail#appspot.gserviceaccount.com",
I then generate a token using the format illustrated by the link at the top.
However when I put that $theCreatedToken in this curl ....
$url = 'https://localhost-42d67.firebaseio.com/Devices.json?auth=' .$theCreatedToken;
$arr = array("success" =>array("iPhone"=>500));
$data_string = json_encode($arr);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
echo $result = curl_exec($ch);
I get this error
{
"error": "Expected an ID token, but was given a custom token."
}
If I remove the ?auth=' .$theCreatedToken; it works.
What am I doing wrong? I have searched this extensively but there is no answer.
I hope someone is able to help.
Best
It's pretty confusing, but I got it worked by using this library and the service accounts JSON generated in Firebase settings.
https://github.com/kreait/firebase-php
I also wrote this library to make it work with Guzzle 5 and PHP 5.6
https://github.com/luqmanrom/firebase-php
Apparently, it uses Bearer token in Authorization header instead of passing the auth token in query strings. The token is fetched from the Google OAuth2 server.
Hopefully it helps
Related
I am new to GCP. I have a function which outputs a CSV file to the GCP Cloud Storage. I am trying to access the file using PHP.
What I have done so far:
I have created a service account using GCP IAM and have given it access as Storage Object Viewer.
I have also obtained the json key from the IAM.
What commands would I need to use in my PHP script (hosted on a different web server) to retrieve the file using CURL and how do I use the json authentication key?
I apologize in advance if this is in the documentation somewhere, I found it very convoluted and over whelming. Any advice or direction is appreciated.
Update:
Based on the comments below here is a link to the google-cloud-php github which I found. I am not sure if this is the best resource to begin.
You can make use of the Cloud Storage library for php, more specifically, how to download objects.
First of all you have to get an accesstoken for Authentification. For this you need the json authentification key.
This page was a great help for me:
https://www.it-swarm.dev/de/curl/wie-kann-man-mit-curl-eine-verbindung-zum-google-drive-api-herstellen/806069468/
Maybe this PHP-code helps you a little bit:
function get_Google_accesstoken($scope,$credfile,$proxy,$timetoexpiration){
#Developers Info at developers.google.com/identity/protocols/oauth2/service-account
$GoogleApiKeyInfo=GoogleApiKeyInfo($credfile);
$Header=array();
$Header["alg"]="RS256";
$Header["typ"]="JWT";
$ClaimSet["iss"]=$GoogleApiKeyInfo["client_email"];
$ClaimSet["scope"]=$scope;
$ClaimSet["aud"]=$GoogleApiKeyInfo["token_uri"];
$ClaimSet["iat"]=time();
$ClaimSet["exp"]=$ClaimSet["iat"]+($timetoexpiration);
$Jws=base64_encode(json_encode($Header)).".".base64_encode(json_encode($ClaimSet));
$OpenSslRslts=openssl_sign($Jws,$Signature,$GoogleApiKeyInfo["private_key"],OPENSSL_ALGO_SHA256);
$Jwt=$Jws.".".base64_encode($Signature);
$SendVars=array();
$SendVars["grant_type"]=("urn:ietf:params:oauth:grant-type:jwt-bearer");
$SendVars["assertion"]=$Jwt;
$SendVars=http_build_query($SendVars);
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $GoogleApiKeyInfo["token_uri"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $SendVars);
$headers = array();
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
if (curl_errno($ch)){
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
$response=json_decode($response);
return $response;
}
you find hints for $scope at developers.google.com/identity/protocols/oauth2/scopes
$proxy is only used if you need a proxy and $timetoexpiration has no influence, because your accesstoken is always valid for 60 minutes
Seems like a simple task but despite having read their docs I can't figure it out. I've gotten a Storefront Access Token, as per https://help.shopify.com/en/api/storefront-api/getting-started. Then I've used it in the CURL request below. However this just returns: {"errors":"[API] Invalid API key or access token (unrecognized login or wrong password)"}
I found their documentation a bit confusing as they have quite a few different APIs, and whilst it seems that this Storefront Access Token should work for this particular API, perhaps it doesn't?
$url = "https://mysite.myshopify.com/admin/api/2019-07/products/count.json";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$headers = array(
'X-Shopify-Storefront-Access-Token: 2400d...........a999'
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
print_r( $result);
curl_close($ch);
If you are using the Stronfront API your request should point to
https://mysite.myshopify.com/api/2019-07/products/count.json
and not to
https://mysite.myshopify.com/admin/api/2019-07/products/count.json
In addition Storefront Api request are different from the standard ones, have that in mind.
I have tried the following code and receive a message saying my particular request is not supported, I cannot find any solutions that are not python for the v20 api. any help would be appreciated on what to use or where im going wrong
My error message is:
{"errorMessage":"Requested HTTP method is not supported for supplied
endpoint."}
<?php
$ch = curl_init();
$vars = "price=B&granularity=M5&count=20";
curl_setopt($ch, CURLOPT_URL,"https://api-fxpractice.oanda.com/v3/instruments/EUR_USD/candles");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$vars); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = [
'Content-Type: application/json',
'Authorization: Bearer access-token',
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$server_output = curl_exec ($ch);
curl_close ($ch);
print $server_output ;
?>
My goal here is to successfully connect and get the response from the endpoint containing data. I have no python experience which is why im trying curl or even a javascript solution would work. Am i just not understanding this API at all?
Two things that stand out in the code are:
that there is no actual authorisation code. I don’t know if you have removed it for security while posting, or if you don’t realise you need to create a practice account and get an authorisation code for it? Both are free.
Your code curl_setopt($ch, CURLOPT_POST, 1); suggests you are trying a POST, whereas a GET is required for the \instruments endpoint.
But the simplest thing I can suggest that might help is to look at the following Github bash script that has taken OANDA's V1 API bash cURL example, and updated it for the v2 rest API.
https://github.com/p-burke/oanda-REST-v2-API-bash-script
I am trying to use PHP and CURL to connect to Microsoft Dynamics API so I can read client data from the CRM. The API guide can be found here:
https://msdn.microsoft.com/en-gb/library/mt593051.aspx
I've been into the Azure portal and set up a new application, and it gives me the credentials to use (client id, secret, etc.) and the url end points. Using these credentials I am able to successfully connect to the CRM and retrieve a bearer access token, but I am unable to get any further.
When I attempt to use the token to return data I receive the below error message:
HTTP Error 401 - Unauthorized: Access is denied
My assumption would be that I must be passing the token correctly?
My code is below.
<?php
// Step 1 - Use the credentials supplied by CRM to get an access token (this bit works okay)
$credentials = array(
'grant_type'=>'client_credentials',
'username'=>'xxxxxxxx',
'password'=>'xxxxxxxx',
'client_id'=>'xxxxxxxxxxxx',
'client_secret'=>'xxxxxxxxxx',
);
$urlSafeCredentials = http_build_query($credentials);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://login.microsoftonline.com/xxxxxxxxxxxxxx/oauth2/token');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $urlSafeCredentials);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
$response = curl_exec($ch);
$result = json_decode($response);
curl_close($ch);
// A BEARER access token is successfully returned
$token = $result->access_token;
// Step 2 - Use the access token to request data from the CRM (this bit fails with HTTP Error 401 - Unauthorized: Access is denied)
$ch = curl_init('https://clientspecificurl.crm4.dynamics.com/api/data/v8.1/accounts');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/x-www-form-urlencoded','Authorization: Bearer '.$token));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
print_r($response); // 401 Unauthorized ?!
?>
As far as I can tell there is nothing else to configure at the back end, any help would be much appreciated.
Based on the parameters to acquire the token, you were mixing the client credentials flow and resource owner password flow and lack of resource parameter.
The client credentials flow requires parameters grant_type,client_id,client_secret,resource and the value of grant_type is client_credentials.
The resource owner password credentials flow requires grant_type,client_id,client_secret,username,password,resource and the value of grant_type is password.
If you were using the client credentials flow, you can refer this blog for acquiring the token. And if you were using the resource owner password, you can refer this thread.
Details about difference of the flows in Oauth 2 please refer RFC 6749.
I wrote a lightweight PHP class for working with Dynamics 365 online Web API. You can find it here.
BTW in your code you should try "password" inside the grant_type instead of "client_credentials"
I am really stuck with this. I have exchanged the token returned by the LinkedIn JSAPI up to step 3 where I receive the oauth_token and oauth_token_secret. I am using the oauth-php library from here and following instruction from LinkedIn and SO. In the LinkedIn docs step 4 uses the pecl oauth library to set the token and token secret. Oauth-php doesn't have seem to have a similar method. My token looks similar to this 00--xx11xx22-123a-0000-0a0a-12312asda1231asd so not really like the OAuth 2.0 tokens.
I am trying to call this method with my exchanged oauth_token, but I keep getting an invalid token response. Clearly I am missing some step. Any help at all is greatly appreciated.
function linkedin_api_get($exchanged_oauth_token) {
$url = 'https://api.linkedin.com/v1/people/~';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "MyLinkedInConnect");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Authorization: Bearer " . $exchanged_oauth_token,
"x-li-format: json"
));
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response);
}
I guess this token can't be used as a bearer. But how do I exchange this token to a bearer token? Or how do I use the oauth token and oauth token secret correctly without the PECL oauth library?