Clear all Facebook profile fields and manually fill out the registration form? - facebook

You know how users can clear the pre-populated form and revert to normal registration?
I'm developing an iframe registration app and when the user clears the form fields, it looks like the signed_request is still valid (if upon load the user was logged into facebook).
Anyone know how we are supposed to know if the user is really using FB info or registration info? I previously thought the session would tell us but my session is still valid after the
user hits "clear form".
// Check to make sure we have a signed_request object, if not, redirect to home
var sreq = Request.Form["signed_request"];
if (string.IsNullOrEmpty(sreq))
{
Response.Redirect(WebConstants.SiteConstants.Home);
}
var app = new FacebookApp();
WHy is app.UserId still populated if the user clears the FORM!
How do I detect that we really want to integrate with FB or not ?
thanks!

I agree about the authentication vs registration but I think the Facebook API is not clearing the authentication cookie correctly because it is still valid if you clear the form or logout (i'm using iFrame registration), so I guess I'm looking for a best practice since when I get the signed-request, the id is the authenticated user so the only work-around I have right now is to check for String.IsEmptyOrNull( on the password field) - which tells me that this user did not use facebook registration). I think this is a hack but if anyone knows the "proper" way to take a signed request and convert it to an object please comment on my approach. It is kinda amazing that we still have to write a ton of code for what should be a straight forward approach to getting what we need. I've seen tons of complaints about FB development and they are mostly true - the Google API is not this frustrating and FB makes it almost impossible to test different environments as well (not to mention the famous cookie problems with localhost).
Problem : App.UserId is still the authenticated user after clearing the iframe form or logging out of FB - go figure.
Solution : check the presense of password field - this tells us that we have a non-fb registration going on....
C#.NET for all the minority out there.
// Check to make sure we have a signed_request object, if not, redirect to home var sreq = Request.Form["signed_request"]; if (string.IsNullOrEmpty(sreq)) { Response.Redirect(WebConstants.SiteConstants.Home); }
JObject meObject = null;
var app = new FacebookApp();
if (app.SignedRequest != null)
{
meObject = JObject.Parse(app.SignedRequest.Dictionary["registration"].ToString());
// Access meObject
JavaScriptSerializer ser = new JavaScriptSerializer();
fbReg = ser.Deserialize<FBRegistration>(meObject.ToString());
if (fbReg != null)
{
// 02 Feb 2011 - MCS - bug in facebook API, does not delete cookie if logout of FB
// We check to see if we have password - then - we know we can check the UserId
if (String.IsNullOrEmpty(fbReg.password))
{
// FB Registration
FacebookUserId = app.UserId;
}
else
{
FacebookUserId = 0;
// Non FB Registration

Registration and authentication are two completely different things. Just because the user "clears" a form does not log them out of facebook. The C# SDK is just detecting if a signed_request exists and is valid.

Related

Facebook UserId returned from Azure Mobile Services keeps changing within the same Windows Phone app

I'm a newbie to app development. I am building a Windows Phone 8.1 app and have followed the tutorial here: http://azure.microsoft.com/en-us/documentation/articles/app-service-mobile-dotnet-backend-windows-store-dotnet-get-started-users-preview/ to add authentication using Facebook. Everything seems to work fine, except that every now and again it appears to stop bringing back any data from my Azure database. Further investigation revealed that the UserId that is being shown from the code below, changes periodically (although I can't quite work out how often it changes).
// Define a member variable for storing the signed-in user.
private MobileServiceUser user;
...
var provider = "Facebook";
...
// Login with the identity provider.
user = await App.MobileService.LoginAsync(provider);
// Create and store the user credentials.
credential = new PasswordCredential(provider,
user.UserId, user.MobileServiceAuthenticationToken);
vault.Add(credential);
...
message = string.Format("You are now logged in - {0}", user.UserId);
var dialog = new MessageDialog(message);
dialog.Commands.Add(new UICommand("OK"));
await dialog.ShowAsync();
This code is identical to the code in the tutorial. The Facebook app settings (on the Facebook developers site) confirm that I am using v2.3 of their API so I should be getting app-scoped UserIds back. I have only ever logged in with one Facebook account, so I would expect the UserId to be the same each time, but they're not. The UserId is prefaced with 'sid:', which someone on the Facebook developers group on Facebook itself says stands for Session ID, which they would expect to change, but if that's the case, I can't work out where to get the actual UserId from that I can then store in my database and do useful things with. I'm sure I must be doing something basic wrong, but I have spent hours Googling this and cannot (unusually) find an answer.
Any help would be greatly appreciated.
Thanks!
So dug deeper. This is how Mobile Apps work (I was thinking from a Mobile Services perspective). The issue here is that the Gateway doesn't provide static SIDs, which is what User.userId provides. The work around to this is listed in the migration doc.
You can only get the Facebook AppId on the server.
ServiceUser user = (ServiceUser) this.User;
FacebookCredentials creds = (await user.GetIdentitiesAsync()).OfType< FacebookCredentials >().FirstOrDefault();
string mobileServicesUserId = creds.Provider + ":" + creds.UserId;
You should note, that this Id is directly connected with your Facebook App registration. If you ever want to migrate your App to a new Facebook App, you'd have to migrate them. You can also use the Facebook AppId to look up the user's global facebook Id via the Facebook Graph API, which you could use between applications. If you don't see yourself using multiple apps, etc., you can use the Facebook AppId just fine.
Hard to tell what's going on to cause you to use a SID instead of the Faceboook token (which like Facebook:10153...).
It may be faster to rip out the code and reimplement the Auth GetStarted. Maybe you missed a step or misconfigured something along the way. If you have the code hosted on github, I can try to take a look.
Another thing you can do is to not trust the user to give you their User id when you save it to a table. On your insert function, you can add it there.
function insert(item, user, request) {
item.id = user.userId;
request.execute();
}
That should, theoretically, be a valid Facebook token. Let me know if that doesn't work; can dig deeper.

HWIOAuthBundle, how to manually authenticate User with a Facebook access token?

I have a website (Symfony2) with HWIOauthBundle used to connect with Facebook and everything works fine.
Now, I'm trying to build an iOS app with Cordova and Ionic framework (AngularJS) and I want to authenticate my user with Facebook :
With $cordovaFacebook, I authenticate my user and get a valid Facebook access token, that's ok
I try to use this access token to authenticate my user on the server-side with HWIOauthBundle :
GET http://..../login/facebook?code=MY_FACEBOOK_ACCESS_TOKEN
Symfony rejects my request with this log :
INFO - Matched route "facebook_login" (parameters: "_route": "facebook_login")
INFO - Authentication request failed: OAuth error: "Invalid verification code format."
So my question is : how can I authenticate my user on both front and back end with Facebook connect?
Thanks :)
I've also been wondering how to implement a server side login with the HWIOAuthBundle.
I didn't find any solution on the web, so I coded the functionnality based on hints I've read on the net.
Basically, you have to :
authenticate the user on your app
make an http request to your server with the Facebook token.
ont the server side, check if the token is for your Facebook app, and retrieve the user's Facebook ID.
Get your user from the DB based on the fetched ID.
Here's my Symfony controller:
public function getSecurityFbAction($token)
{
// Get the token's FB app info.
#$tokenAppResp = file_get_contents('https://graph.facebook.com/app/?access_token='.$token);
if (!$tokenAppResp) {
throw new AccessDeniedHttpException('Bad credentials.');
}
// Make sure it's the correct app.
$tokenApp = json_decode($tokenAppResp, true);
if (!$tokenApp || !isset($tokenApp['id']) || $tokenApp['id'] != $this->container->getParameter('oauth.facebook.id')) {
throw new AccessDeniedHttpException('Bad credentials.');
}
// Get the token's FB user info.
#$tokenUserResp = file_get_contents('https://graph.facebook.com/me/?access_token='.$token);
if (!$tokenUserResp) {
throw new AccessDeniedHttpException('Bad credentials.');
}
// Try to fetch user by it's token ID, create it otherwise.
$tokenUser = json_decode($tokenUserResp, true);
if (!$tokenUser || !isset($tokenUser['id'])) {
throw new AccessDeniedHttpException('Bad credentials.');
}
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->findUserBy(array('facebookId' => $tokenUser['id']));
if (!$user) {
// Create user and store its facebookID.
}
// Return the user's JSON web token for future app<->server communications.
}
I throw the Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException exceptions to handle login errors on my app.
Of course, you really should use https because you will be exchanging sensible information.
I don't know if it's the best way to do it but it works well.
Hope it helps !
Well, I think that Symfony doesn't actually reject your request. Facebook is. I'm not sure if this might help, but I know that a bunch a problems can happen when dealing with the Facebook Auth :
Do you know if the tool sends, along with the code parameter, a redirect_uri parameter ? If so :
Did you check that your redirect_uri HAS a trailing slash at the end ? See this
Silly question, but did you check that your app_id is the same when you got authorized via Cordova ?
Check that your redirect_uri DOES NOT have any query parameter.
Check that the redirect_uri that you use during the whole process is the same all the time.
Overall, it seems that your issue is almost all the time related to the redirect_uri URI format.

Facebook PHP SDK usage stand alone - how do the Facebook sessions/cookies work?

I'm utilizing the Facebook PHP SDK on its own. I do not want to use the JS SDK at all.
Because getUser(); from the SDK can return a user id even if the user is not logged in, I have opted for using a try/catch statement to check if the user is logged in.
try
{
$me = $CI->facebook->api('/me');
$CI->our_fb['is_fb']='YES';
echo "hello";
}
catch(FacebookApiException $e)
{
echo "catch";
}
This statement is included in the global include file of all of my files (for simplicity).
So, depending on the situation, I generate a Facebook login URL. The expected functionality is that the user logins to Facebook, authorises the app, is returned to the redirect URI set in the login URL at which point the try statement will execute, and $CI->our_fb['is_fb'] will be set.
This is however not happening.
If the user is already logged into Facebook and the app is authorised, it works perfectly. SUCCESS
If the user is not logged into Facebook, once redirected the variable is not set. FAILURE
If the user is logged in but the app is NOT authorised after redirect the variable is not set. FAILURE.
In the latter two cases if you simply refresh the page, the variable is set - SUCCESS. Refreshing the page is however unnecessary/pointless extra effort.
My problem is that if you need to login to FB/or authorise the app e.g the first time you login with FB, you have an additional unneeded refresh, and I don't know why.
I suspect it is something to do with the cookie/session? Which saves the access token that I assume is returned/passed to the SDK automatically not being set at the same time?
Anyone got any ideas?
If you're having an app on facebook (tab or canvas). PHP SDK only get the User ID on initial loading of a page because a signed_request is sent with the request to your app.
But, when the app refreshes, the signed_request is lost (as it's facebook who send it).
So, in this case, you can append the signed_request to every URLs your use in your app - but that's really not optimal as the signed_request won't be regenarated - neither refreshed.
Your only real option is to rely on the JS SDK to set cookie correctly and allow getUser to work as expected. This is required because you're considered as a third-party app in Facebook (being in an iframe) and most browser will block you from setting cookies - so you need a work around handled by the JS SDK for you. You can search for cross-domain cookies or third-party cookie for explanation about the workarounds, but these workaround only work via JS scripting and iframe management.
Also, be sure to setup the JS SDK correctly: channel file, cookie allowed, and send P3P headers (for IE).
You can also check this related question: A proper approach to FB auth
About website, the same mostly stays (but you have no signed_request). At this point, seriously consider using the JS SDK as it's way easier. Or else, you can make sure your app flow follow these guidelines: https://developers.facebook.com/docs/concepts/login/login-architecture/
The way I am seeing this is, you are trying to avoid that refresh if the user is not logged in and precedes to log in after the page has initially loaded.
So what you can do is make an ajax request to another page on your site, say for example id.php, which just loads the php sdk and echo $userid; and then you can grab the user id after login without the refresh.
Basically the cookie is used to save the signed request and session is used to save 'state', 'code', 'access_token', 'user_id'. If the above are present PHP SDK uses them, no matter if they are valid or not.
I think your problem lies in the CODE sent by facebook. Specifically these lines in base_facebook.php:
if ($code && $code != $this->getPersistentData('code')) {
$access_token = $this->getAccessTokenFromCode($code);
...
protected function getAccessTokenFromCode($code, $redirect_uri = null) {
if (empty($code)) {
return false;
}
if ($redirect_uri === null) {
$redirect_uri = $this->getCurrentUrl();
}
...
Because CODE is issued for specific url sometimes there is such situation: Visitor arrives on www.example.com. He givies permissions and is redirected to example.com/login. But the code is not valid there, so the getUserAccessToken returns false. When you refresh the page you get same urls and everything's fine.
You're on the right track of not using getUser() because as I wrote above it's taken from the session if available.

Facebook getUser() function returning user ID after logout

I'm developing using the Facebook PHP SDK.
I wanted to make it so that when the user logs out of Facebook, they will automatically be logged out of my website too.
I am using the following code to detect the session, using the session cookie:
$facebook->getUser();
For some reason, the getUser() function still returns the user's Facebook ID, even after they have logged out of Facebook on their website.
Am I to detect the session first using another Function?
On the official documentation example here, is the following excerpt from their comments:
// Get User ID
$user = $facebook->getUser();
// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
This lead me to believe that the session cookie for Facebook would become unset upon Facebook logout?
Kind Regards,
Luke
I have the same issue!
The FB PHP SDK saves those things into the $_SESSION!
You can delete them like this when your user clicks logout:
$_SESSION['fb_'.APP_ID.'_user_id'] = '';
$_SESSION['fb_'.APP_ID.'_access_token'] = '';
Although this is not the final solution, it works for now.
I appreciate comments and solutions on that!
I want to give an alternative, in a way you don't have to handle session stuff. Although, I must warn you this is slower than cleaning up the session, because it relies on a new request. What we're doing in the code below is to check on Facebook if the token is still valid. Here it's:
try {
$facebook->api('/me','GET');
$logged = true;
} catch(FacebookApiException $e) {
$logged = false;
}
In my case, I was doing everything using the JavaScript SDK, so I couldn't clean session on logout. But in my landing page, I was needing a work around to check it before send the response back.
If you're facing something like this, definitely a good solution.
The problem seems to be in php-sdk in basefacebook.php at line 567
protected function getSignedRequestCookieName() {
return 'fbsr'.$this->getAppId();}
This method returns the name of the cookie the sdk is looking for. However, javascript-sdk uses 'fbs_' prefix. Change this to 'fbs_' and it works fine.
return 'fbs'.$this->getAppId();}
$facebook->destroySession();
To destroy the session you can also use:
$facebook->destroySession();

is admin on facebook pages

I looked around and could not find anything to do this (well it was not obvious or semi-obvious)
So say i have a facebook application that offers a service that people will pay for during use. The average user can come on and "Subscribe" to it, while the admin of those pages can perform an activity that will cost them money (make me money).
I do not want hacking attempts or anything to hurt our product. So, how can i verify that someone is an admin using the PHP SDK.
What we are currently doing is storing the $_POST["signed_request"] in $_SESSION's data and working with that. Either the $_POST or $_SESSION is not safe 100% (firesheep).
Is there any way to verify this? graph api?
Okay, first things first. To retrieve the signed_request and check if the user is an admin you would use something like:
$signed_request = $facebook->getSignedRequest();
if ($signed_request['page']) { // Loaded in a page tab
if ($signed_request['page']['admin']) {
// Current user is admin
} else {
// Normal user
}
} else { // Canvas view
}
Now I'm not sure what do you mean by:
What we are currently doing is storing the $_POST["signed_request"] in
$_SESSION's data and working with that.
Because if you are using the PHP-SDK then you don't need to worry about storing the signed_request in the session since the SDK will handle it for you.
Now for the last part:
Either the $_POST or $_SESSION is not safe 100% (firesheep).
That's not true, the signed_request is useless without your app secret key to decode it. So even if someone was able to obtain it, it won't compromise your application. Read more about signed_requests here.