Google create enterprise 403 error on get signup url request - php

I am trying to create new enterprise in my emm provider.
here is code
error_reporting(0);
$projectId = "api-7288506515928753288-19357";
$callbackUrl = url('emm/create/enterprise');
$callbackUrl = str_replace('http://', 'https://', $callbackUrl);
$authFile = storage_path('app/key/dv-505f70dd1be9.json');
putenv("GOOGLE_APPLICATION_CREDENTIALS={$authFile}");
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope('https://www.googleapis.com/auth/androidenterprise');
// returns a Guzzle HTTP Client
$httpClient = $client->authorize();
$response = $httpClient->post("https://www.googleapis.com/androidenterprise/v1/enterprises/signupUrl?callbackUrl={$callbackUrl}");
$response = json_decode( $response->getBody()->getContents() );
// $request->session()->put('signupUrlName', $response->name);
// $request->session()->put('signupUrl', $response->url);
return json_encode( $response );
I got below responce
{
error: {
errors: [
{
domain: "androidenterprise",
reason: "forbiddenNotAnMdm",
message: "The caller is not registered as an MDM."
}
],
code: 403,
message: "The caller is not registered as an MDM."
}
}
I already checked on https://content-androidmanagement.googleapis.com/v1/signupUrls api.
This api is working right .
in short authentication is right with proper scope . But can t able to figure out responce.

To use the Google Play EMM API you need to be registered in the EMM Community.
But you shouldn't need to use this API anymore, instead you should use the new Android Management API that gives the same capabilities, and more.

Related

PHP: How to make an api call with api key authorization using Guzzle?

I'm trying to create a client to connect an IBM-Watson bot service using Guzzle for an application constructed in Laravel, but it fails when attempting to create a new session of the service, I got the error 401: Unauthorized. I'm not using basic authorization, instead I'm trying to connect by api-key authorization.
function start_bot_session() {
//Api Key de Watson.
$api_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
//ID bot (Watson).
$assistant_id = '9c1c426d-cd33-49ec-a3bc-f0835c3264b5';
//URL service.
$url = 'https://gateway.watsonplatform.net/assistant/api/v2/assistants/';
//Method for start a new session.
$method = $assistant_id.'/sessions?version=2019-02-28';
$client = new \GuzzleHttp\Client(["base_uri" => $url]);
$response = $client->request('POST', $method, [
'headers' => [
'Authorization:' => $api_key
]
]);
return response;
}
Is there any way I can fix this?
Can you tell me some alternatives to make api call instead of using Guzzle?

Cannot use object of type Google_Auth_LoginTicket as array

I was performing Google Sign in on Android Application for the first time. At the client side, I obtained the access token and sent to the PHP server via POST.
By referring to Google's Documentation, the code I used in backend is as follows:
$id_token = $_POST['id_token'];
$CLIENT_ID = "** MY WEB APPLICATION CLIENT ID **";
$client = new Google_Client(['client_id' => $CLIENT_ID]);
$client->setAuthConfigFile('client_secret.json');
...
$payload = $client->verifyIdToken($id_token);
if ($payload) {
$userid = $payload['sub'];
} else {
echo "Invalid Token";
}
When obtaining user id, the error is : "Cannot use object of type Google_Auth_LoginTicket as array"
I am pretty new to Google sign in. Please point out what all has gone wrong.
Found It. I made some modifications to the code
$token_data = $client->verifyIdToken($id_token)->getAttributes();
$user_id = $token_data['payload']['sub'];
Now the user id is retrieved fine.

Keep getting 403 Forbidden from Google API (using PHP client library v1)

Okay... I have to say I don't have enough experience on using Google's API, so I'll try to explain as detail as I could.
I need to use PHP to grab the Cloud storage's data, so I tried my credential with gsUtil to grab data from bucket and it works; But when I try to use PHP library to grab data, the API replied me with this content:
"error": {
"errors": [
{
"domain": "global",
"reason": "forbidden",
"message": "Forbidden"
}
],
"code": 403,
"message": "Forbidden"
}
Since it didn't tell me exactly which step is wrong, so I searched around this site and tried everything which looked similar, but the Situation stands.
Here is the Configuration on my Google Dev. Console:
Api Manager > Overall > Enabled APIļ¼š
(a)Drive API.
(b)Cloud Storage.
(c)Cloud Storage JSON API.
Api Manager > Credentials:
(a)Api Key / OAuth 2.0 ID / Service Acc. Key are created.
(b)Server IPs are added to the Api key's accept IP list.
(c)Service Account have the Editor permission to the Project, service acc key is bind to this account too.
In PHP:
$email = '<my gmail>';
$scope = 'https://www.googleapis.com/auth/cloud-platform';
$apiKey = '<my api key>';
$oAuthId = '<OAuth ID>';
$serviceAcc = '<service account id>#developer.gserviceaccount.com';
$keyFileLocation = $_SERVER['DOCUMENT_ROOT']. "/<p12 file>";
$bucketId = '<my bucket id>';
$list = array();
$client = new Google_Client();
$client->setApplicationName("gp-api");
$client->setDeveloperKey($apiKey);
$cred = new Google_Auth_AssertionCredentials (
$serviceAcc,
array($scope),
file_get_contents($keyFileLocation)
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired())
$client->getAuth()->refreshTokenWithAssertion($cred);
if($client->getAccessToken()) {
$reqUrl = "https://www.googleapis.com/storage/v1/b/$bucketId/o/";
$request = new Google_Http_Request($reqUrl, 'GET', null, null);
$httpRequest = $client->getAuth()->authenticatedRequest($request);
if ($httpRequest->getResponseHttpCode() == 200) {
$objects = json_decode($httpRequest->getResponseBody());
foreach ($objects->items as $object) {
$list[] = $object->mediaLink;
}
}
else {
echo $httpRequest->getResponseHttpCode(); // This is where I got the 403
}
}
Please tell me if I missed something.
Ok, I got the Problem: it must impersonate the User account which have the privilege to access the API scope that I mentioned in program.
So some additional codes must be added as following:
$email = '<email account which could access that api>';
$scope = 'https://www.googleapis.com/auth/cloud-platform';
$apiKey = '<my api key>';
$oAuthId = '<OAuth ID>';
$serviceAcc = '<service account id>#developer.gserviceaccount.com';
$keyFileLocation = $_SERVER['DOCUMENT_ROOT']. "/<p12 file>";
$bucketId = '<my bucket id>';
$list = array();
$client = new Google_Client();
$client->setApplicationName("gp-api");
$client->setDeveloperKey($apiKey);
$cred = new Google_Auth_AssertionCredentials (
$serviceAcc,
array($scope),
file_get_contents($keyFileLocation),
'notasecret',
'http://oauth.net/grant_type/jwt/1.0/bearer',
$email
);
Woooooyaaaaa, another problem solved! time to move up for next problem.

google plus oauth sign in with php not enough information

I'm here:
https://developers.google.com/+/web/signin/server-side-flow
On steps 7 and 8 there is reference to the variable $request yet this variable is not initialized, therefore copying and pasting from their provided example doesn't work, I get 500 server error just with the first line from step 7 or step 8 alone, step 8 line using $request, never initialized from their example.
$code = $request->getContent();
The sample code you are looking at uses Twig which contains $request and $response values to simplify RESTful endpoints.
The following code does the equivalent code without the Twig dependencies:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_PlusService.php';
$client = new Google_Client();
// CLIENT ID / Secret from https://code.google.com/apis/console
$CLIENT_ID = 'YOUR_CLIENT_ID';
$client->setClientId($CLIENT_ID);
$client->setClientSecret('YOUR_CLIENT_SECRET');
// CUSTOM redirect URI assuming code from JavaScript callback
$client->setRedirectUri('postmessage');
$plus = new Google_PlusService($client);
// Code from the client (returned in signinCallback, or in token on Android)
$code = file_get_contents('php://input');
// Exchange the OAuth 2.0 authorization code for user credentials.
$client->authenticate($code);
$token = json_decode($client->getAccessToken());
// Verify the token
$reqUrl = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=' .
$token->access_token;
$req = new Google_HttpRequest($reqUrl);
$tokenInfo = json_decode(
$client::getIo()->authenticatedRequest($req)->getResponseBody());
// If there was an error in the token info, abort.
if ($tokenInfo->error) {
print $tokenInfo->error;
}
// Make sure the token we got is for our app.
if ($tokenInfo->audience != CLIENT_ID) {
print "Token's client ID does not match app's.";
}
print 'Token from result: ' . print_r($token, true);

PHP/Twitter oAuth - Automated Tweets

Im using the following code to read to consumer_key and consumer_secret from config.php, pass it to twitter and retrieve some bits of information back from them.
What the script below attempts to do is 'cache' the request_token and request_secret. So in theory I should be able to reuse those details (all 4 of them to automatically tweet when required).
<?php
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
$consumer_key = CONSUMER_KEY;
$consumer_secret = CONSUMER_SECRET;
if (isset($_GET["register"]))
{
// If the "register" parameter is set we create a new TwitterOAuth object
// and request a token
/* Build TwitterOAuth object with client credentials. */
$oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request = $oauth->getRequestToken();
$request_token = $request["oauth_token"];
$request_token_secret = $request["oauth_token_secret"];
// At this I store the two request tokens somewhere.
file_put_contents("request_token", $request_token);
file_put_contents("request_token_secret", $request_token_secret);
// Generate a request link and output it
$request_link = $oauth->getAuthorizeURL($request);
echo "Request here: " . $request_link . "";
die();
}
elseif (isset($_GET["validate"]))
{
// This is the validation part. I read the stored request
// tokens.
$request_token = file_get_contents("request_token");
$request_token_secret = file_get_contents("request_token_secret");
// Initiate a new TwitterOAuth object. This time we provide them with more details:
// The request token and the request token secret
$oauth = new TwitterOAuth($consumer_key, $consumer_secret,
$request_token, $request_token_secret);
// Ask Twitter for an access token (and an access token secret)
$request = $oauth->getAccessToken();
// There we go
$access_token = $request['oauth_token'];
$access_token_secret = $request['oauth_token_secret'];
// Now store the two tokens into another file (or database or whatever):
file_put_contents("access_token", $access_token);
file_put_contents("access_token_secret", $access_token_secret);
// Great! Now we've got the access tokens stored.
// Let's verify credentials and output the username.
// Note that this time we're passing TwitterOAuth the access tokens.
$oauth = new TwitterOAuth($consumer_key, $consumer_secret,
$access_token, $access_token_secret);
// Send an API request to verify credentials
$credentials = $oauth->oAuthRequest('https://twitter.com/account/verify_credentials.xml', 'GET', array());
// Parse the result (assuming you've got simplexml installed)
$credentials = simplexml_load_string($credentials);
var_dump($credentials);
// And finaly output some text
echo "Access token saved! Authorized as #" . $credentials->screen_name;
die();
}
?>
When i run /?verify&oauth_token=0000000000000000 - It works however trying to resuse the generated tokens etc... I get a 401
Here is the last bit of code where I attempt to reuse the details from Twitter combined with my consumer_key and consumer_secret and get the 401:
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
// Read the access tokens
$access_token = file_get_contents("access_token");
$access_token_secret = file_get_contents("access_token_secret");
// Initiate a TwitterOAuth using those access tokens
$oauth = new TwitterOAuth($consumer_key, $consumer_key_secret,
$access_token, $access_token_secret);
// Post an update to Twitter via your application:
$oauth->OAuthRequest('https://twitter.com/statuses/update.xml',
array('status' => "Hey! I'm posting via #OAuth!"), 'POST');
Not sure whats going wrong, are you able to cache the details or do i need to try something else?
You can't store the OAuth tokens in cache and to more than 1 request with it, as OAuth is there to help make the system secure, your "oauth_token" will contain some unique data, this token will only be able to make one call back to twitter, as soon as the call was made, that "oauth_token" is no longer valid, and the OAuth class should request a new "oauth_token", thus making sure that every call that was made is secure.
That is why you are getting an "401 unauthorized" error on the second time as the token is no longer valid.
twitter is still using OAuth v1 (v2 is still in the draft process even though facebook and google already implemented it in some parts)
The image below describes the flow of the OAuth authentication.
Hope it helps.
A while ago I used this to connect to twitter and send tweets, just note that it did make use of some Zend classes as the project was running on a zend server.
require_once 'Zend/Service/Twitter.php';
class Twitter {
protected $_username = '<your_twitter_username>';
protected $_token = '<your_twitter_access_token>';
protected $_secret = '<your_twitter_access_token_secret>';
protected $_twitter = NULL;
//class constructor
public function __construct() {
$this->getTwitter();
}
//singleton twitter object
protected function getTwitter() {
if (null === $this->_twitter) {
$accessToken = new Zend_Oauth_Token_Access;
$accessToken->setToken($this->_token)
->setTokenSecret($this->_secret);
$this->_twitter = new Zend_Service_Twitter(array(
'username' => $this->_username,
'accessToken' => $accessToken,
));
$response = $this->_twitter->account->verifyCredentials();
if ($response->isError()) {
throw new Zend_Exception('Provided credentials for Twitter log writer are wrong');
}
}
return $this->_twitter;
}
//send a status message to twitter
public function update( $tweet ) {
$this->getTwitter()->status->update($tweet);
}
}
In your second script, it looks like you aren't setting the Consumer Key and Consumer Secret when you create your TwitterOAuth instance.
// Initiate a TwitterOAuth using those access tokens
$oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token_secret);

Categories