Google Plus OAuth PHP 401 (Unauthorized) - php

I am trying to setup authentication with google plus using their tutorial. I followed the directions verbatim, changing the client id and the client secret in signin.php. For the record, the google plus API is enabled in the google developer console. I update file permissions as instructed as well (chmod +x signin.php and chmod -R 555 vendor/). However, upon loading my authentication URL (which happens to be at the auth_test/ sub directory of my domain, and clicking the sign in button, the console throws a 401 (unauthorized) for the get request sent /activites. I have researched the problem and see that this can be caused by an invalid token, but I dont see how that can be because everything has been setup in singin.php. Much help would be appreciated...

You need to reset the state of your app if disconnected to refresh the $tocken.
Google API office Docs on Handling API Errors
401: Invalid Credentials
Invalid authorization header. The access token you're using is either
expired or invalid.
{ "error": {
> "errors": [
> {
> "domain": "global",
> "reason": "authError",
> "message": "Invalid Credentials",
> "locationType": "header",
> "location": "Authorization",
> }
> ],
> "code": 401,
> "message": "Invalid Credentials" } }
Suggested action: Refresh the access token using the long-lived
refresh token. If this fails, direct the user through the OAuth flow,
as described in Authorizing Your App
Also its is clearly commented in singin.php at line no. 98 :
// Normally the state would be a one-time use token, however in our
// simple case, we want a user to be able to connect and disconnect
// without reloading the page. Thus, for demonstration, we don't
// implement this best practice.
//$app['session']->set('state', '');
Thus in your case it appears that your app is disconnected and thus causing the $token to become empty. Hence forcing this code block at line no: 91
if (empty($token)) {
// Ensure that this is no request forgery going on, and that the user
// sending us this connect request is the user that was supposed to.
if ($request->get('state') != ($app['session']->get('state'))) {
return new Response('Invalid state parameter', 401);
}

Related

How to write to a sheet with Google Sheets API without oAuth consent screen

I'm writing a script in PHP to automate the process of grabbing data from a Database and inserting it into a google sheet.
Since it's going to be running at 15 minute intervals and Oauth consent screen isn't really the best option.
Is there another option to get the necessary authorization to write to the sheet without the need of signing in via browser?
Most of the examples I've seen in the documentation and online use a consent screen.
If I try this:
$client = new Google_Client();
$service = new Google_Service_Sheets($client);
Which would work with the Text-to-Speech API I get this (naturally):
> PHP Fatal error: Uncaught Google\Service\Exception: { "error": {
> "code": 401,
> "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid
> authentication credential. See
> https://developers.google.com/identity/sign-in/web/devconsole-project.",
> "errors": [
> {
> "message": "Login Required.",
> "domain": "global",
> "reason": "required",
> "location": "Authorization",
> "locationType": "header"
> }
> ],
> "status": "UNAUTHENTICATED" } }
The link in the error message just guides you through making a consent screen. From what I could find online if i were to only be reading a file there wouldn't be a problem, but writing to it, even if i set the sheet to public, requires authentication.
Note: This is all running in a Gcloud VM instance
You can use a service account and then share the sheet with that service account.
Go to console.cloud.google.com and login with the account containing the sheet
Add the Google Sheets API (go to APIs and Services, look up Google Sheets API, add it)
Go back to APIs and Services and click on Credentials
Click on Create credentials -> Service account
Fill in required stuff (mainly Service account name, and give it Owner role) and press done
Click on the service account you just created
Go to keys tab -> Add key -> Create new key -> JSON
This should give you a key to use. This is your client_secret.json. Use
$client->setAuthConfig('./client_secret.json') or
$client->setAuthConfigFile('./client_secret.json')
depending on the version of the php google api client you are using.
Also, make sure you set the appropriate scope using
$client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
Share the sheet from your drive with the created service account and give it editorial permissions

YouTube Content ID API with Service Account returns Forbidden error

I've created a service account for use with the YouTube Content ID API, I'm following the steps under Set up your service account on:
https://developers.google.com/youtube/partner/guides/oauth2_for_service_accounts
The steps seem to be a bit outdated, but I'm managed to create a service account and I've got the email address. I didn't know if I needed to assign a Role so I didn't.
I visited the Content ID users page and invited the service account user:
The problem is I get the error the request could not be completed, but when I refresh the page, the user appears to be added successfully.
Well, when I'm making requests using this service account, I'm getting forbidden errors. For example the below error is when I'm trying to get a list of claims.
{
"error": {
"errors": [
{
"domain": "global",
"reason": "forbidden",
"message": "Forbidden"
}
],
"code": 403,
"message": "Forbidden"
}
}
But some requests work, like listing/inserting labels, listing content owners.
All the permissions are assigned for the user so I'm not sure what the reason for the forbidden errors are.
Here's the PHP code:
$OAUTH2_KEY_FILE = 'key.json';
$client = new \Google_Client();
$client->setAuthConfig($OAUTH2_KEY_FILE);
$client->setScopes([\Google_Service_YouTubePartner::YOUTUBEPARTNER]);
$youtubePartner = new \Google_Service_YouTubePartner($client);
dd($youtubePartner->claims->listClaims([
'onBehalfOfContentOwner' => 'XXX'
]));

Seeking code example for OAuth 2.0 with Google Ad Exchange seller-API

First things first:
The goal is to pull reports from via ADX seller API.
I followed the tutorial, created a Project in the GDC, activated the adx-seller-API and added an OAuth 2.0 client ID just to make sure both types, "Web application" and "Other".
The code is easy enough, I got the google-api-php-client via composer and used the minimal example:
<?php
require_once 'vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->addScope('https://www.googleapis.com/auth/adexcange.seller');
$service = new Google_Service_AdExchangeSeller($client);
$result = $service->accounts->listAccounts();
print_r($result);
?>
However running the code only yields an exception:
Google_Service_Exception: { "error": { "errors": [ { "domain": "global", "reason": "required", "message": "Login Required", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Login Required" } } in [SNIP]\vendor\google\apiclient\src\Google\Http\REST.php on line 105
So basically 401: Login required
I also used both generated JSON for client_secrets.json, only the "other" one works.
If I use the Google API Explorer it works just fine, oddly the accountId that is talked of everywhere seems to be the DFP-ADX Publisher ID in case anyone is ever wondering.
I've no idea why this isn't working? Am I missing something important or doing something wrong?
In case it helps, I tried the same with Python, for some reason I get as far as to the authentication via browser, the adexchangeseller.dat is created and then it pops a 403: User does not have an Ad Exchange Seller account. which is hilarious considering it does and works via Google API Explorer.
Any help, even a push towards a decent tutorial is appreciated a lot of researching only led to dead ends.

How to remove duplicate Facebook Access Tokens?

I have 100 Active Facebook access tokens.
For each account I have more than one access token.
I want to keep only one token for each account and want to delete the others.
And i don't want to do this manually so please post a PHP script which check all the tokens and keep only one active token for each account.
In such a case the simplest way to validate an access token is to issue the following request
https://graph.facebook.com/me?fields=id&access_token=#accesstoken
If the provided access token is not valid or expired Facebook will just return an error message of some sort. Such as :
{
"error": {
"message": "Error validating access token: This may be because the user logged out or may be due to a system error.",
"type": "OAuthException",
"code": 190,
"error_subcode": 467
}
}
For a valid access token the result will somehow look like this
{
"id": "ID_VALUE"
}

FQL app access tokens

Note: App access tokens are being used here so there is no login or permissions required.
My app access token is valid according to the Facebook App access token debugger
My FQL request is correct according to the Graph API explorer (for FQL)
However when I attempt a FQL search using my app access token:
$fql_query_url = 'https://graph.facebook.com/'.'fql?q='.urlencode($fql_query) . '&access_token=' . urlencode($acctoken);
I get the response:
{
"error": {
"message": "(#200) Must have a valid access_token to access this endpoint",
"type": "OAuthException",
"code": 200
}
}
The code I'm using literally worked two days ago but not it appears to be broken.
Does anyone know what is going on? I've looking into the app access token depreciation after 60 days but surely this would appear as an invalid token in the Facebook access token debugger. Also isn't the error message different if the app access token is depreciated.

Categories