Facebook TokenResponseException with Laravel 4.1 and oauth-4-laravel - php

I'm getting a TokenResponseException from Laravel when I try to login to my web site with Facebook using oauth-4-laravel.
OAuth \ Common \ Http \ Exception \ TokenResponseException
Failed to request resource.
Using Facebook's JavaScript API works like its supposed to, so I'm pretty sure my application is configured correctly.
Are there any known issues that might cause this problem? Am I doing something wrong, or is this a bug in the library?
With the exception of a redirect line that works around another bug, my code is identical to the example code at the GitHub page. I think the exception is thrown when I try to get the token from the Facebook Service object.
Here's the code:
public function loginWithFacebook() {
// get data from input
$code = Input::get( 'code' );
// get fb service
$fb = OAuth::consumer( 'Facebook' );
// check if code is valid
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
// This was a callback request from google, get the token
$token = $fb->requestAccessToken( $code );
// Send a request with it
$result = json_decode( $fb->request( '/me' ), true );
$message = 'Your unique facebook user id is: ' . $result['id'] . ' and your name is ' . $result['name'];
echo $message. "<br/>";
//Var_dump
//display whole array().
dd($result);
}
// if not ask for permission first
else {
// get fb authorization
$url = $fb->getAuthorizationUri();
// return to facebook login url
// ref: https://github.com/artdarek/oauth-4-laravel/issues/27
//return Response::make()->header( 'Location', (string)$url );
return Redirect::to((string)$url);
}
}
And a screenshot:

I had this exact same problem. It turns out that my issue was that my return_uri was missing a trailing slash, which through off the entire process. Make sure that when you're calling it you've added it.
$fb = OAuth::consumer('Facebook','http://url.to.redirect.to/');
NOT
$fb = OAuth::consumer('Facebook','http://url.to.redirect.to');

first try to load file_get_contents("https://www.facebook.com");
if allow_url_fopen=0 was set in the php.ini it will not work so you need to change it to allow_url_fopen=1

The weirdest thing i have your problem with google not with facebook, so here is my code maby it helps you fix your fb problem
public function loginWithFacebook() {
// get data from input
$code = Input::get( 'code' );
// get fb service
$fb = OAuth::consumer( 'Facebook' );
// check if code is valid
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
// This was a callback request from facebook, get the token
$token = $fb->requestAccessToken( $code );
// Send a request with it
$result = json_decode( $fb->request( '/me' ), true );
$message = 'Your unique facebook user id is: ' . $result['id'] . ' and your name is ' . $result['name'];
echo $message. "<br/>";
//Var_dump
//display whole array().
dd($result);
}
// if not ask for permission first
else {
// get fb authorization
$url = $fb->getAuthorizationUri();
// return to facebook login url
return Redirect::to( (string)$url );
}
}

Since my previous answer was deleted.. Let's try again..
--
After some debugging I think I got it. Commenting out the error_reporting part visible in your code snippet will already tell you a lot. The file_get_contents call got a 401 Unauthorized because the tokens were no longer valid.
After changing code, start your auth process from the beginning and don't refresh your url half-way, that wil cause the error.

The problem should be here $token = $fb->requestAccessToken( $code );
When I tried var_dump it, I get this.
object(OAuth\OAuth2\Token\StdOAuth2Token)[279]
protected 'accessToken' => string 'your-accessToken' (length=180)
protected 'refreshToken' => null
protected 'endOfLife' => int 1404625939
protected 'extraParams' =>
array (size=0)
empty
Try this and check what you've get as accessToken. Anyway, your function loginWithFacebook working fine with me.

I had the same problem. I was trying to access facebook graph. It wasn't that it could not access the URL, it was that Facebook was returning a 400 error because I wasn't passing parameters through. Try connecting to HTTPS on a site that will have a working HTTPS connection. E.g. Try this:
file_get_contents("https://www.namhost.com");
If that works, you must see why the HTTPs connection you are connecting to is failing, because the problem isn't that you can't connect to HTTPs, but rather that what you are connecting to isn't liking the request.

Related

Failed to request resource with facebook and twitter login oauth

I have an issue with my Facebook and Twitter login but only in production (I also have a Google login but it works fine in production). When I run it on localhost I can login without problems. When in production I'm getting a TokenResponseException exception.
I'm using artdarek's oauth-4-laravel but there doesn't seem to be much support in the Issues area.
My code is as follows:.
public function loginWithFacebook() {
// get data from input
$code = Input::get( 'code' );
// $OAuth = new OAuth();
// $OAuth::setHttpClient('CurlClient');
// get fb service
$fb = OAuth::consumer( 'Facebook','http://fisicloud.com/facebook/' );
// check if code is valid
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
// This was a callback request from facebook, get the token
$token = $fb->requestAccessToken( $code );
Below is the error I'm seeing. How can I fix this?

How to get google contact list using artdarek-oauth-4-laravel?

I am using artdarek-oauth-4-laravel for the Login to my website via Facebook, twitter and google.
Login part is working fine. But I want to get some more data from these api, like if user is registering through the google then I am looking for their general info as well as google contact list, or if the user is registering from Facebook then I am trying to get the /me and /friend-list etc.
Here, I am just taking the case of google.
I have set the config like this
'Google' => array(
'client_id' => '***********************************',
'client_secret' => '***********************************',
'scope' => array('userinfo_email', 'userinfo_profile', 'https://www.google.com/m8/feeds/'),
),
My Controller Function is this:-
public function loginWithGoogle()
{
$code = Input::get( 'code' );
$googleService = OAuth::consumer( 'Google' );
if ( !empty( $code ) )
{
$token = $googleService->requestAccessToken( $code );
// $result = json_decode( $googleService->request( 'https://www.googleapis.com/oauth2/v1/userinfo' ), true );
$result = json_decode( $googleService->request( 'https://www.google.com/m8/feeds/contacts/default/full' ), true );
echo json_encode($result);
}
else {
// get googleService authorization
$url = $googleService->getAuthorizationUri();
// return to google login url
return Redirect::to( (string)$url );
}
}
This code leads me to the google api and asks for all the permission that I have set in the scope of the service. Here once I got the access token after exchanging the code parameter with the api, I am calling the url to return me the contact list but it fails. And I am getting this message from the laravel :-Failed to request resource.
If I call the commented $result request, it returns me the result.
So, I wanted to know how can we use this library for the data other than login and register. In case of retrieving facebook friendlist the same thing happens but the login works. (My Facebook App has the permission to get friendlist).
Any help is appreciated.
Check this response, https://stackoverflow.com/a/26488136/434790.
It worked for me. The culprit: alt=json to be added to https://www.google.com/m8/feeds/contacts/default/full

Laravel 4 - Google Sign In

I am new in Laravel
I am testing Google Sign In with oauth-4-laravel by following the guide. I am managed to select my google account but after that it returned the URL like:
http://host.com/google/loginwithgoogle?code=4/SXVJ-Ou9xLt60kZ-OR68DxxxxxXFD.kqJwUtyEmhcfXE-sT2ZxxxxxxxxxxxxigI
How can I handle this route within my Route.php file? My current code on Route.php is:
Route::get('login', function()
{
return View::make('login');
});
Route::controller('google', 'GoogleController');
And my GoogleController.php code
public function postLoginwithgoogle(){
// get data from input
$code = Input::get( 'code' );
// get google service
$googleService = OAuth::consumer( 'Google' );
// check if code is valid
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
// This was a callback request from google, get the token
$token = $googleService->requestAccessToken( $code );
// Send a request with it
$result = json_decode( $googleService->request( 'https://www.googleapis.com/oauth2/v1/userinfo' ), true );
$message = 'Your unique Google user id is: ' . $result['id'] . ' and your name is ' . $result['name'];
echo $message. "<br/>";
//Var_dump
//display whole array().
dd($result);
}
// if not ask for permission first
else {
// get googleService authorization
$url = $googleService->getAuthorizationUri();
// return to facebook login url
return Redirect::to( (string)$url );
}
}
I suspect is the 'post' and 'get' but how should I code it? Thanks!
No route is needed. Just redirect the user to the URL:
Redirect::to('<URL provided by Google>');
See details in the documentation.
There is no need to specif a route to POST artdarek/oauth-4-laravel works with GET by adding the token after the ? in the url. So basicly you don't need any extra routes.
There are some problems with your route though.The example you posted here assumes that Google redirects an authenticated user back to the same url with a valid token. In your case I gather that that is http://host.com/google/loginwithgoogle, and you want to use http://host.com/google. For this to happen you need to edit the route as follow:
Route::controller('google', 'GoogleController#postLoginwithgoogle'); //I would remove the "post" part of the name since it is misleading
when you redirect to host.com/google now when someone wants to login with Google then is should work.

Could not retrieve a valid Token response from Token URL + Twitter API

I am doing the login using twitter in my zend framework application. But after authenticating from twitter it showing the following error :
Message:Could not retrieve a valid Token response from Token URL: /oauth/access_token?oauth_consumer_key=xxxxxxxxxxxxxxx&oauth_nonce=xxxxxxxxxxxxxxxxxxxx&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1352270857&oauth_token=xxxxxxxxxxxxx&oauth_version=1.0
&oauth_verifier=xxxxxxxxxxxxxxxxxxxxx&oauth_signature=wv5gdop77NA9BeZI7ilQcEFsqGH8CeR4%3D Invalid / expired Token
Following is my code :
public function twittercallbackAction() {
$path = realpath(APPLICATION_PATH . '/../library/');
set_include_path($path);
$config = array(
"callbackUrl" => "http://" . $_SERVER['HTTP_HOST'] . "/register/twittercallback",
"siteUrl" => "http://twitter.com/oauth",
"consumerKey" => "xxxxxxxxxxxxxx",
"consumerSecret" => "xxxxxxxxxxxxxxxxxxxx"
);
$consumer = new Zend_Oauth_Consumer($config);
if (!empty($_GET) && isset($_SESSION['TWITTER_REQUEST_TOKEN'])) {
$token = $consumer->getAccessToken($_GET, unserialize($_SESSION['TWITTER_REQUEST_TOKEN']));
// Now that we have an Access Token, we can discard the Request Token
// get users timeline
// $_SESSION['TWITTER_REQUEST_TOKEN'] = null;
} else {
// Mistaken request? Some malfeasant trying something?
exit('Invalid callback request. Oops. Sorry.');
}
}
I am searching this issue on google but not getting any solution.
How can I deal with this issue.
Thanks
Finally I solved it myself.... :-)
The problem was twitter updated their api url:
From
http://twitter.com/statuses/user_timeline.json?
To
https://api.twitter.com/1/statuses/user_timeline.json?
and it gets fixed.
I tested your code, which I assume you got from http://framework.zend.com/manual/1.12/en/zend.oauth.introduction.html, and it works properly. Here are a few things to check:
Is your consumer app key/secret valid?
Does your server have the correct date/time set?
What's your code for generating your request token?

Facebook PHP SDK get access token using php

I am using the following code to post to Facebook:
require('facebook.php');
$fb = new Facebook(array('appId' => 'MY APP ID','secret' => 'MY APP SECRET','cookie' => true));
$result = false;
$feed_dir = '/401868882779/feed/'; //to the UID you want to send to
$acToken = "MY ACCESS TOKEN";
$url = 'URL';
$link = $url . 'event.php?id=' . $id;
if (isset($picture))
{
$picture = $url . 'uploads/' . $picture;
}
else
{
$picture = $url . 'images/blank100x70.png';
}
$msg_body = array('access_token' => $acToken,'name' => $noe_unsecured,'message' => $link,'link' => $link,'description' => $description_unsecured,'picture' => $picture);
try
{
$result = $fb->api($feed_dir, 'post', $msg_body);
}
catch (Exception $e)
{
$err_str = $e->getMessage();
}
but I need to update the access token manually every time it changes. I am sure there's solution but I cant find it.. I tried lots of scripts and nothing worked.
It is possible.
Check: http://developers.facebook.com/docs/reference/php/facebook-setAccessToken/
Depending on when you perform the wall post, you might need to request the offline_access permission. This will convert your access_token into a format that does not expire so there would be no need to refresh the token.
A simple solution...remove the access_token!
You simply don't need it as long as you got the publish_stream permission!
I believe there are multiple methods to do this:
- you can use the method already provided in the PHP SDK getAccessToken which returns the current access token being used by the sdk instance, more info at this url.
- However you need not use an access token to call the api() method, once you ask the user for the publish_stream permission, as already mentioned by #ifaour. Hence you can do something like this example, scroll to the subheading Post a link to a User's wall using the Graph API.
- Then, you have another three options
i) either get a new access token using the method here, if you are posting when the user is currently using your app, otherwise you can try the next 2 options
ii) get offline access
iii) i'm not sure of this, but you might want to try with an app access token which can be obtained this way.

Categories