LinkedIn Api - Uncaught exception 'OAuthException' - php

I'm currently attempting to install a login button for LinkedIn onto my website. I'm trying to go step by step as the developers section shows. After I wrote the code to get a request token and checked it using print_r.
define("my consumer key");
define("my consumer secret");
$oauth = new OAuth(my consumer key, my consumer secret);
//The first item of business is getting a request token
$request_token_response = $oauth->getRequestToken('https://api.linkedin.com/uas/oauth/requestToken');
if($request_token_response === FALSE) {
throw new Exception("Failed fetching request token, response was:"
. $oauth->getLastResponse());
} else {
$request_token = $request_token_response;
}
print "Request Token:\n";
printf(" - oauth_token = %s\n", $request_token['oauth_token']);
printf(" - oauth_token_secret = %s\n", $request_token['oauth_token_secret']);
print "\n";
I got "Fatal error:Uncaught exception 'OAuthException'...Peer certificate cannot be authenticated with known CA certificates". The line that was called for the error is below
$request_token_response = $oauth->getRequestToken('https://api.linkedin.com/uas/oauth/requestToken');
I am not understanding what that error is trying to tell me so that I can fix the problem. I would appreciate and tips or guidance to help me better understand what this error message is trying to convey and how to fix it.

It seems that the library is trying to verify the SSL certificate and it cannot do so. You could disable ssl checks via the method OAuth::disableSSLChecks. I assume you are using the following pecl extension http://www.php.net/manual/en/class.oauth.php. If not the client library you are using should have a method to disable the SSL certificate verification.
....
...
$oauth = new OAuth(my consumer key, my consumer secret);
$oauth->disableSSLChecks();
..
...
Ideally you would do it right after instantiation

Related

Fat Free Use Google OAuth + Google API

I'm trying the following thing for quite a while now and am heavily struggling...
On a website, I first want to authenticate a user with his Google Account using OAuth. Therefore, I'm using this library. In order to get it working, I used $f3->set('AUTOLOAD','vendor/ikkez/f3-opauth/lib/opauth/'); to load the PHP files and then used the following code to create the routes and make the authentication possible:
$f3 = \Base::instance();
// load opauth config (allow token resolve)
$f3->config('vendor/ikkez/f3-opauth/lib/opauth/opauth.ini', TRUE);
// init with config
$opauth = OpauthBridge::instance($f3->opauth);
// define login handler
$opauth->onSuccess(function($data){
header('Content-Type: text');
//$data['credentials']['token'];
});
// define error handler
$opauth->onAbort(function($data){
header('Content-Type: text');
echo 'Auth request was canceled.'."\n";
print_r($data);
});
So far so good, thats all working fine, once permission is granted from Google I get the correct callback, also including the login token.
Now the next step is, that after user gave permission for that (by authenticating), I want to check, if the user subscribed to a specific channel on Youtube (and afterwards saving that information to my DB, printing it at the first step would be enough though).
Now I did my homework for multiple hours in trying to figuring out how it works...
What I (in general found) is that the following curl request should give me the desired result:
curl \
'https://youtube.googleapis.com/youtube/v3/subscriptions?part=snippet%2CcontentDetails&forChannelId=UC_x5XG1OV2P6uZZ5FSM9Ttw&mine=true&key=[YOUR_API_KEY]' \
--header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
--header 'Accept: application/json' \
--compressed
I then tried to sent this curl request with PHP, substituting the API KEY with my Google API Key and "YOUR_ACCESS_TOKEN" with the token I got from OAUTH.... However, it's throwing an error, saying "request had insufficient authentication scopes"... That seems to be because when checking the PHP example from Google, I have to provide the Scopes I'm using - in my case https://www.googleapis.com/auth/youtube.readonly.
The PHP code provided by Google is the following:
<?php
/**
* Sample PHP code for youtube.subscriptions.list
* See instructions for running these code samples locally:
* https://developers.google.com/explorer-help/guides/code_samples#php
*/
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new Exception(sprintf('Please run "composer require google/apiclient:~2.0" in "%s"', __DIR__));
}
require_once __DIR__ . '/vendor/autoload.php';
$client = new Google_Client();
$client->setApplicationName('API code samples');
$client->setScopes([
'https://www.googleapis.com/auth/youtube.readonly',
]);
// TODO: For this request to work, you must replace
// "YOUR_CLIENT_SECRET_FILE.json" with a pointer to your
// client_secret.json file. For more information, see
// https://cloud.google.com/iam/docs/creating-managing-service-account-keys
$client->setAuthConfig('YOUR_CLIENT_SECRET_FILE.json');
$client->setAccessType('offline');
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open this link in your browser:\n%s\n", $authUrl);
print('Enter verification code: ');
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Define service object for making API requests.
$service = new Google_Service_YouTube($client);
$queryParams = [
'forChannelId' => 'UC_x5XG1OV2P6uZZ5FSM9Ttw',
'mine' => true
];
$response = $service->subscriptions->listSubscriptions('snippet,contentDetails', $queryParams);
print_r($response);
This let's me run into a new issue... Trying to use this code, I'm getting the error, that Google_Client is not known as class... I then went ahead and installed Google Client with Composer and tried to use vendor/autoload.php in order to use the class.... However, when including the autoload.php, I get the error Fatal error: Cannot declare class Prefab, because the name is already in use... This seems to be the case, because the f3-opauth declares this Prefab class already and then the google apiclient tries to declare it again... However, I didn't manage to to include google apiclient without the autoload...
You see, I really tried a lot and I've been working on this for about 5-6 hours today, only getting that one API request to work and I don't know what else to try...
Any hint on how to get it working would be appreciated - if there's any hint on doing it a completely other way, I'd be willing to change it as well, as the project itself just started.
Summarizing, what I'm trying to do is the following:
-> User can log in on Website with his Youtube/Google Account
-> When authenticating, its checked, if the User is a Subscriber of a specific channel. Next step would be to also check, if he is a channel member of this speicific channel. Both information would need to be saved to database
-> after that, user can always log in into his account with Google again and in the database, you can find the information if the user is subscriber and/or channel member of this channel..
Thanks in advance!
I'm not sure if this will help with your exact use case, but I've worked with Google APIs in the past with Fat-Free. I couldn't get it to work right off the bat, so I installed and got it working with the Google Client/API/SDK. Once I got that working, then I worked backwards to see if I could make it work with Fat-Free. One of the things that I noticed I was running into was missing fields in the Oauth request. access_type was one that got me as well as approval_prompt. I know that you said you've gotten your access token thus far, so it may not apply, but it could for future requests. Here's some example code I've got working to generate an oauth URL for Google Sign in, and then to process the request and make the call to the userinfo portion.
<?php
class App_Auth {
public static function generateOauthUrl() {
$fw = Base::instance();
$Oauth = new \Web\OAuth2();
$Oauth->set('client_id', $fw->get('google.client_id'));
$Oauth->set('scope', 'profile email');
$Oauth->set('response_type', 'code');
$Oauth->set('access_type', 'online');
$Oauth->set('approval_prompt', 'auto');
$Oauth->set('redirect_uri', $fw->SCHEME.'://' . $_SERVER['HTTP_HOST'] . $fw->BASE.'/oauthRedirect');
return $Oauth->uri('https://accounts.google.com/o/oauth2/auth', true);
}
public static function processAuthCodeAndGetToken($auth_code) {
$fw = Base::instance();
$Oauth = new \Web\OAuth2();
$Oauth->set('client_id', $fw->get('google.client_id'));
$Oauth->set('client_secret', $fw->get('google.client_secret'));
$Oauth->set('scope', 'profile email');
$Oauth->set('access_type', 'online');
$Oauth->set('grant_type', 'authorization_code');
$Oauth->set('code', $auth_code);
$Oauth->set('approval_prompt', 'auto');
$Oauth->set('redirect_uri', $fw->SCHEME.'://' . $_SERVER['HTTP_HOST'] . $fw->BASE.'/oauthRedirect');
return $Oauth->request('https://oauth2.googleapis.com/token', 'POST');
}
public static function getOauthUserInfo($access_token) {
$Oauth_User_Info = new \Web\OAuth2();
return $Oauth_User_Info->request('https://www.googleapis.com/oauth2/v2/userinfo', 'GET', $access_token);
}
One other error that has bitten me in the backside was we would get our access token from Google and then store it in the database for subsequent requests. We would get that scopes error you mentioned request had insufficient authentication scopes. We eventually figured out that the access_token was longer than our database field (VARCHAR(32) if I remember right) so we needed to make our database field longer so it would store the whole thing.
Hopefully one of those triggers something for you to figure out your issue.

How to solve User profile request failed in Google social login

When I try to login with google authentication, gives me an error. I have use Hybrid authentication use. It's work on HTTP but not working on HTTPS.
Please see the error:
User profile request failed. Most likely the user is not connected to
the provider and he should authenticate again. Ooophs, we got an
error: User profile request failed! Google returned an error:
exception 'Exception' with message 'The Authorization Service has
return
Code
$hybridauth = new Hybrid_Auth( $setting );
$provider = $hybridauth->authenticate( $this->session->data['provider']);
//get the user profile
$profile = $provider->getUserProfile();
$this->register($this->session->data['provider'], (array)$profile);
The OAuth2Client class has recently been changed in order to be compliant with the RFC6749 specifications.
Check them out here: https://www.rfc-editor.org/rfc/rfc6749#section-2.3.1
I believe this only affected POST requests.
Get the update in this PR: https://github.com/hybridauth/hybridauth/pull/707
I believe this has been merged into the master now as well, so you could just grab a new copy of the code and update locally.

fecing 'Google_Auth_Exception' wror fetching OAuth2 access token, message: 'invalid_client'' error

I am trying to fetch mail from Google through gmail api
while authenticate the Google_Client after receiving the token i am getting this error
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error fetching OAuth2 access token, message: 'invalid_client'' in
my code is simple using google-api-php-client-master and my code is as follow
require_once('config.php');
require_once 'autoload.php';
$client = new Google_Client();
$client->setScopes(array(
'https://www.googleapis.com/auth/plus.login',
'profile',
'email',
'openid',
'https://www.googleapis.com/auth/gmail.readonly',
'https://mail.google.com/',
));
$client->setApplicationName($config->social['google']->app_name);
$client->setClientId($config->social['google']->client_id);
$client->setClientSecret($config->social['google']->client_secret);
$client->setRedirectUri($config->social['google']->Redirect_URI);
$client->setDeveloperKey($config->social['google']->api_key); // API key
$gclient='';
print_r($_GET);
$token=new stdclass;
if(!isset( $_SESSION['google_token']))
{
$gclient=$client->authenticate($_GET['code']);//error occurs hare
$_SESSION['gclient']=$gclient;
if($gclient)
{
$_SESSION['google_token'] = $client->getAccessToken();
}
print_r($gclient);
}
I have checked my credentials several times and they were all correct
would some one please help me on it
I had the same problem but my solution was extreamly easy and frustrating.
When you copy the "Client secret" in API Credentials on your Google Developers Console they add a space after the "Client secret". Be sure to delete it!
$client_secret = "hf83nd93hd93j39dj9 ";<--
As Mario M. explained, there's an additional space when you copy the Client Secret. You have to make sure you got it right.
I got the same error - Error fetching OAuth2 access token, message: 'invalid_client', but in my case it was due to not verified domain. Therefore if you are creating credentials for a Web application or something similar and received the same error;
Check there's no additional space at the end of Client secret
Make sure your domain is verified
In my case I had to set the Client Secret file
$client->setAuthConfigFile(WWW_ROOT . 'files\json\client_secret_google_api.json');
and that solved my problem. Hope it helps someone.

oauth 401 unauthorized error for heroku app fitbit

I've got a heroku app and I am running with Auth0 as the way of logging in via oauth... I have some code more or less the same as from the fitbit api php tutorial - "completeAuthorization.php". It looks a bit like:
$oauth = new OAuth($conskey, $conssec, OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_AUTHORIZATION);
$oauth->enableDebug();
}
catch( OAuthException $E )
{
print_r($E);
}
echo 'done new oauth';
$oauth->setToken($_SESSION['access_token'], $_SESSION['access_token_secret']);
echo 'done set token';
// Fitbit API call (get activities for specified date)
//http://api.fitbit.com/1/user/28C9GG/activities/date/2013-12-01.xml
$apiCall2 = 'http://api.fitbit.com/1/user/'.$_SESSION['userid'].'/activities/date/2014-02-25.xml';
echo $apiCall2;
// Performing API call
$oauth->fetch($apiCall2);
//$oauth->fetch($apiCall);
var_dump($oauth->getLastResponse());
I get the user id, and the session secret and token etc. from the Auth0 response from my index.php page, but I save them in a session to keep them on my get activities page.
But when I go to my page that does this after I log in with Auth0, I get this error:
http://api.fitbit.com/1/user/28C9GG/activities/date/2014-02-25.xml Fatal error: Uncaught exception 'OAuthException' with message 'Invalid auth/bad request (got a 401, expected HTTP/1.1 20X or a redirect)'
I am also only able to get this far on my webserver which has a pecl oauth extension installed, but heroku does not and I have no idea how to get it on Heroku, any ideas on this or why I get the above error?
Here is an example that might be useful:
https://github.com/auth0/Auth0-PHP/tree/master/examples/fitbit
In particular look at callback.php where there is a call to fitbit API
Matias

LinkedIn API OAuth Problem

I'm using the PEAR OAuth Class to access the LinkedIn developer API and I've come across a bit of a problem. I can authorize my application but when it comes to getting an accessToken I'm receiving this error:
Edit:
Code after Adam's suggestions
public function oauth_access()
{
session_start();
$token = $_GET['oauth_token'];
$verifier = $_GET['oauth_verifier'];
$secret = $_SESSION['trequest_token_secret'];
$key = "****";
$secret = "****";
$oauthc = new OAuth($key, $secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
$oauthc->setToken($token, $secret);
$oauthc->setNonce(rand());
try
{
$access_token_info = $oauthc->getAccessToken("https://api.linkedin.com/uas/oauth/accessToken");
$_SESSION['laccess_oauth_token']= $access_token_info['oauth_token'];
$_SESSION['laccess_oauth_token_secret']= $access_token_info['oauth_token_secret'];
$_SESSION['loauth_verifier'] = $verifier;
}
catch (OAuthException $e)
{
echo $e->getMessage();
}
}
But I'm now getting a different error:
Invalid auth/bad request (got a 401, expected HTTP/1.1 20X or a redirect)
You don't need to manually compute the signature, as pecl/oauth will do that for you.
Also, you're telling the library to pass the data in the Authorization HTTP header. That is a good place to have it. Then you are passing it via a query parameter. That is permitted, but less optimal. (You may actually be passing it in two places.) Also, pecl/oauth will automatically generate the proper timestamp.
When I first started, I found this blog post to be a good first start.
Or you can use the LinkedIn PHP library listed by Paul. It's also a good place to begin, if you don't want to reuse pecl/oauth because you're using that someplace else.

Categories