I'm writing some backend script for a twitter app and heres how it's going
On the app you click a button that sends you to login.php on my server which logs into my database connects to twitter with my consumer key and secret: $to = new TwitterOAuth($consumer_key, $consumer_secret);
$tok = $to->getRequestToken();
$request_link = $to->getAuthorizeURL($tok);
and then writes the token and secret to the database, sets a session equal to the id in the database of the token and secret and then redirects to the "$request_link"
You then go through the process of logging in and such on twitter and it redirects you to callback.php on my server
Callback.php consists of logging into the database again, getting the new token and secret, and then writing the new token and secret to the database and then prompts you to go back to the app
Then on the app, all I'm trying to do is access the basic credentials$to->get('account/verify_credentials') and it keeps coming back "could not authenticate you"
What am I doing wrong?? Thank you for all the help :)
This is how your last $to should be built before calling verify_credentials:
$to = new TwitterOAuth($consumer_key, $consumer_secret, $tok['oauth_token'], $tok['oauth_token_secret']);
$to->get('account/verify_credentials');
Make sure $tok is the oauth_token and oauth_token_secret you got from:
$tok = $to->getAccessToken();
I assume all the calls are from the same server so there should not be any time sync issues.
Related
I am building a portal where multiple users can log in to their multiple Gmail accounts. I have successfully retrieved the token value, However, I want to store that in my database but I am unable to store it.
Below is the code I am using:
function mInititalize(){
$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://mail.google.com/');
$client->setClientId(Config('gmail.client_id'));
$client->setClientSecret(Config('gmail.client_secret'));
$client->setRedirectUri('http://localhost:81'.Config('gmail.redirect_url'));
$loginURL = $client->createAuthUrl();
return redirect($loginURL);
}
After Redirection or user login
function mGetToken(){
$token = $client->fetchAccessTokenWithAuthCode( 'code'); // here i get the 'code' from login URL
I pass this code to get token I successfully get token
$oAuth = new Google_Service_Oauth2( $client);
$userData = $oAuth->userinfo_v2_me->get(); // get current user detail
}
I want to store $token value in database, but I am getting error message
>Serialization of 'Closure' is not allowed
Please anyone help me to solve this issue. Thanks.
I would suggest storing OAuth credential information for the Google API, not in your database, but through the API itself. If you're intending to use it any authentication manner, you'll run into problems, as the docs state:
Access tokens periodically expire and become invalid credentials for a related API request. Google Identity Platform: Using OAuth 2.0 for Web Server Applications
But, the same docs also show a way that you can set or retrieve the token natively within the API. Since it's data relating to google's auth'ing process, and since it might go stale if you store it, it seems best to just let them handle it and work with the API. The same source:
If you need to apply an access token to a new Google_Client object—for example, if you stored the access token in a user session—use the setAccessToken method:
$client->setAccessToken($access_token);
$client->getAccessToken();
I'm getting the ID Token in my Android app by initiating like this:
GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.server_client_id))
.requestEmail()
.build();
Where server_client_id is my SERVER's Oauth Client ID. Then later I request the token with googleAccount.getIdToken()
Then on my server (PHP), when I verify the token I verify it like this:
$client = new \Google_Client(['client_id' => getenv("GOOGLE_CLIENT_ID")]);
try {
$payload = $client->verifyIdToken($this->idToken);
} catch (\Exception $e){
throw new BadRequestHttpException($e->getMessage());
}
if($payload){
$this->verifyPayload($payload);
} else {
throw new AccessDeniedHttpException("Invalid ID Token");
}
Where GOOGLE_CLIENT_ID is my ANDROID's Oauth Client ID
I'm following this guide: https://developers.google.com/identity/sign-in/android/start-integrating.
On this page it says: https://developers.google.com/identity/sign-in/android/backend-auth
When you configure Google Sign-in, call the requestIdToken method and pass it your server's web client ID.
Hence why I'm using the server_client_id in my Android app. Is this correct?
// Specify the CLIENT_ID of the app that accesses the backend
And this is why I'm using the ANDROID client ID from my server.
Is this right? To be using each other's Oauth client_id's? Or should they both be using the Android CLIENT_ID?
Thanks in advance
OK I figured it out. Both the Android app and Webserver need to use the SERVER's key. Even though I created a client ID for the app using it's key SHA1 and everything.
Send authorisation request from the app, using client_id and public key
As a response you get a temporary token
Send the token to your API. Use it to make another request (from the API to Google), to get a long lived token
Store the long-lived token. Use it to request data from google, f.e. user information
Important: never use server key inside the app
What are the basic steps for setting up a pure server flow facebook SSO, the docs are as usual a little ambiguous?
I set up the flow with javascript popups only to later realise you are not allowed to customise the login buttons.. which when you stick them next google and twitter sso the signin box look terrible.
http://www.codecademy.com/ seem to direct to their own server which then forwards onto a URL like this:
https://www.facebook.com/dialog/oauth?response_type=code
&client_id=212500508799908&
redirect_uri=http%3A%2F%2Fwww.codecademy.com%2Fauth%2Ffacebook%2Fcallback&state=8aac5bc63c5afe8fbabe572021e7750579fefd898d7b4316&
scope=email%2Cpublish_actions
How is this URL being generated? In the facebook docs there is a function "getLoginUrl".. is this being called which generates the correct URL?
I tried directing the user directly from their browser to:
var href = 'https://www.facebook.com/dialog/oauth?' +
'client_id='+app_id+'&'+
'redirect_uri=http://www.mysite.net/authenticate_facebook.php&'+
'scope=email&';+
'state='+$('body').attr('unique');
But the at the facebook php then the following recieving code resulted in errors about the 'state' not matching... I am assuming that the state is not just a random value generate by my server and must be aquired from the facebook server?
require_once(WEBROOT_PRIVATE.'authenticate/facebook-php-sdk/src/facebook.php');
$config = array(
'appId' => 'xxx',
'secret' => 'xxx',
'fileUpload' => false,
'allowSignedRequest' => false
);
$facebook = new \Facebook($config);
$user_id = $facebook->getUser();
if($user_id)
{
try
{
$user_profile = $facebook->api('/me','GET');
}
catch(FacebookApiException $e)
{
error_log($e->getType(), 0);
error_log($e->getMessage(), 0);
}
}
SO, is this correct flow:
1 - Direct the user to my server facebook_auth.php
2 - facebook_auth.php generate the get url and forwards the user onto it
3 - The user, if required logs into facebook, allows my app
4 - my facebook_auth.php script then checks the tokens and talks server to server with facebook to verify the rest
5 - my website then logs the user in
I had a similar issue last week, and tracked it down to the state field being overwritten by multiple calls to getLoginUrl(). Each time you call getLoginUrl(), a new state token is generated in the SDK and stored in the $_SESSION (it's just a random value), so if you call it twice and the user uses the first link to log in, the second call will have reset the SDK's internal state token, and you will get this error in your logs.
The SDK looks for the same state token in the URL coming back after Facebook authorizes the user and redirects them back to your site, and if it doesn't match it will log this error (here's a link to the source).
I'm working on building a small web app connecting into the instagram API. Currently using this library on GitHub which makes things a bit easier. I can connect and initially login fine, and the page will display all user data.
But once you refresh the page all the data is lost, and it appears the script can't find my access token anymore. I tried storing this into a PHP session variable - but maybe I'm doing the whole process incorrectly? I just want to keep the same user session throughout an entire website once the OAuth is performed.
You can check out the small app live here: http://spyrestudios.com/demos/instagram-api/index.php
Additionally my callback URL is http://spyrestudios.com/demos/instagram-api/instagammy.php - this is the script which will work right after you connect. But try refreshing the page and all the data is gone! Also here is my bit of code which *should use the library to store the current user's access token:
session_start();
require_once 'Instagram.php'; // the library code
$config = array(
'client_id' => 'f0d225aa955c4bd9ae563f87f831efab', // Your client id
'client_secret' => '377b77afc1274a89bd2df7d77e934689', // Your client secret
'grant_type' => 'authorization_code',
'redirect_uri' => 'http://spyrestudios.com/demos/instagram-api/instagammy.php', // The redirect URI you provided when signed up for the service
);
// Instantiate the API handler object
$instagram = new Instagram($config);
$accessToken = $instagram->getAccessToken();
$_SESSION['InstagramAccessToken'] = $accessToken;
Really struggling for a solution, so I'd appreciate any help I can get. Willing to post examples of my code if needed..
Thanks in advance!
What you have already looks fine (although I have no experience in Instagram), assuming that $accessToken is actually being stored correctly in the session.
But surely at some point you need to feed back in $accessToken so that it can be verified. Like I said, I've not used Instagram before, so I don't know how you would do this.
Just in case you still care..
The problem is that refreshing is hitting the oauth landing page again when you refresh or back, but there is no authorization for it to collect the information from. In theory you could just wrap your setting of the session variable around a check:
$instagram = new Instagram($config);
$accessToken = $instagram->getAccessToken();
if ($accessToken != '')
$_SESSION['InstagramAccessToken'] = $accessToken;
That would stop an unwanted to call to your oauth landing page from clearing the current session value.
But better still would be to have the landing page redirect to a different page for the display. ie have your instagammy.php end there and add a
header("Location: http://spyrestudios.com/demos/instagram-api/dosomethinghere.php");
die();
That way the user won't ever see the "instagammy.php" page in their history and won't be able to go back to it.
This work for me, instead the original file instagammy.php
$instagram = new Instagram($config);
if ($_SESSION['InstagramAccessToken'] == ''){
$accessToken = $instagram->getAccessToken();
$_SESSION['InstagramAccessToken'] = $accessToken;
}else{
$accessToken = $_SESSION['InstagramAccessToken'];
$instagram->setAccessToken($_SESSION['InstagramAccessToken']);
}
I have an iPhone app which creates a facebook session and I would like to restore this session on my server to hand off some of the work. I have the iPhone app working perfectly fine, it's just that I am having problems restoring the session - the documentation is lacking, at best (from http://wiki.developers.facebook.com/index.php/Facebook_Connect_for_iPhone -"If you want to call the API from your servers, you just need to get the sessionKey and sessionSecret properties from the session and send them back to your servers", that's it).
I think I have a decent start from what docs I have found, and my php page looks like:
require_once 'facebook.php';
$appapikey = 'key';
$appsecret = 'secret';
$userid = 'id';
$sessionKey = 'key';
$facebook = new Facebook($appapikey, $appsecret);
$facebook->set_user($userid,$sessionKey);
However, when I try to login to this page I get the following error:
Fatal error: Uncaught exception 'FacebookRestClientException' with message 'Session key invalid or no longer valid'
I know that the session is valid because I am still logged in on my iPhone app. Does anybody know how to restore a session that was started on Facebook Connect?
Thank you
i spent a lot of time to find answer but found it already:
$this->facebook = new Facebook($appapikey, $appsecret);
$this->facebook->set_user($fb_id, $sessionKey, null, $sessionSecret);
just post sessionSecret with sessionKey to your server and use it with set_user API method
works perfect for me :)