AS3 FacebookDesktop Login fail with OAuthException - #2500 An active access token must be used to query information about the current user - facebook

I think this is because Facebook just made some changes to their login process.
A few days ago, my air app was working with the FacebookDesktop class from the facebook-actionscript-api. Today I opened the project, and noticed that the Facebook login screens are a little different than when I started building my app. After I type my userID and password in, I grant the app access to my public profile, friend list and photos. Then another screen comes up where I grant the app permission to post to my friends on my behalf.
Then the window closes, and I get 'OAuthException 2500 An active access token must be used to query information about the current user.'
When I sign into Facebook through a browser, I see that my app shows up under "Your Apps" but I can't log in and do anything through my app.
I'm using Adobe Flash with GraphAPI_Desktop_1_8_1.swc on OSX Lion.
Here is my code:
public function MyApp(){
FacebookDesktop.init(APP_ID, onInit);
}
protected function onInit(result:Object, fail:Object):void {
if (result) {
trace("onInit, Logged In\n");
} else {
trace("onInit, Not Logged In\n");
var permissions:Array = ["publish_stream", "user_photos"];
FacebookDesktop.login(onLogin, permissions);
}
}
protected function onLogin(result:Object, fail:Object):void {
if (result) {
trace("Logged In as:");
trace(FacebookDesktop.getSession().user.name);
} else {
trace("Login Failed");
trace('code: '+fail.error.code); //code: 2500
trace('message: '+fail.error.message); //message: An active access token must be used to query information about the current user.
trace('type: '+fail.error.type); //type: OAuthException
}
}
I get the same results when I use the FlashDesktopExample provided in the SDK (modified with my app ID of course).
Any help would be great! Thanks in advance!

I ran into this problem, too: the success URL did not have any parameters.
Cadderly82 is correct; it's a problem with secure navigation. Turning off my Facebook account's "Secure Browsing" option fixed the problem, but I didn't want to have to require users to do that.
I was able to solve this by setting ALL of the FacebookURLDefaults values to use "https://".
Now I get a valid user-access-token in the success URL; and I get valid values regardless of my facebook account's secure-browsing setting.

I have figured out the problem:
The LoginWindow class sets the token based on the uri.
This worked fine until the LOGIN_SUCCESS_URL (http://www.facebook.com/connect/login_success.html) and the LOGIN_SUCCESS_SECUREURL (https://www.facebook.com/connect/login_success.html) pages stopped including the access token in the uri.
Hence, the token is never set. Even though my app shows up under the 'Your Apps' section in Facebook after I login, my app still can't do anything without a token.
I have two solutions:
The easiest is to change the LOGIN_SUCCESS_URL and/or the LOGIN_SUCCESS_SECUREURL properties in com.facebook.graph.core.FacebookURLDefaults like the following.
beginning on line 82:
public static var LOGIN_SUCCESS_URL:String = 'http://www.facebook.com/connect/login_success.html';
public static var LOGIN_SUCCESS_SECUREURL:String = 'https://www.facebook.com/connect/login_success.html';
Change to:
public static var LOGIN_SUCCESS_URL:String = 'http://www.yourwebsite.com/';
public static var LOGIN_SUCCESS_SECUREURL:String = 'https://www.yoursecurewebsite.com/';
of course you would use your own website - not 'http://www.yourwebsite.com/'. I tried it using http://localhost/ and it worked great.
Another solution is:
Change com.facebook.graph.windows.LoginWindow with the following code. I have made some changes to my files, so please forgive me if the line numbers are different than what they are in a fresh copy of the SDK.
around line 143:
change:
vars.redirect_uri = FacebookURLDefaults.LOGIN_SUCCESS_URL;
to:
vars.redirect_uri = 'http://localhost/';
In production code, you probably want to use your own website address instead of localhost, but I used localhost for testing purposes.
Then, in the handleLocationChange function (should be around line 168) add this to the else if statements:
}else if (html.location.indexOf ('http://localhost/') == 0) {
loginCallback(getURLVariables(), null);
userClosedWindow = false;
html.stage.nativeWindow.close();
html.removeEventListener(Event.LOCATION_CHANGE, handleLocationChange);
}
As I said before, change localhost to your website address.
I hope this helps!

I was having the same problem for random users and I don't really know if it is a Facebook problem with secure navigation:
Check user properties in Facebook: Security Settings > Secure Browsing
(www.facebook.com/settings?tab=security)
For users with "disabled" state it works fine.
For users with "migration" state it gives the error.
For users with previously "enabled" state it works fine.
When I tried with users in "migration" state and changed to "disabled", it worked fine.
Then if I turned it "enabled", the "migration" state is gone and marked as "enabled", but the error it's still there.
So I guess this is the problem, but don't know how to fix it.

alot has change in a year this is what i think the answer is now
you need a token to login FacebookDesktop.getSession().accessToken
public function MyApp(){FacebookDesktop.init(APP_ID, onInit, FacebookDesktop.getSession().accessToken); }

Related

Unity Facebook SDK: FB.IsLoggedIn / FB.ShareLink issue

I'm trying to create my mobile app user to share my Facebook page and if they do, I give them an in-game item. I'm using the example code provided by Facebook here: https://developers.facebook.com/docs/unity/examples
The first issue is that FB.ShareLink doesn't comeback negative if the user cancels the sharing action. From what I've read, that's on purpose and it only works correctly if the user is logged in and my app is authorized. I tested it and that's true, if I use the login code to first login, it comes back as positive or negative correctly.
The second issue that I'm having though is that FB.IsLoggedIn never comes back negative and I'm not sure how to properly check this because even though it comes back as true, my app is note authorized and FB.ShareLink doesn't return negative when canceled. I start the Login issue and then I press the back arrow to cancel it but FB.IsLoggedIn still comes back as true.
How can I just check if the app is authorized? I'm guessing that's all I need to check before running the FB.ShareLink code.
Any ideas?
Thanks!
First, we try to login asking for the user's e-mail address.
public void LogIntoFacebook() {
List<string> perms = new List<string>() { "email" };
FB.LogInWithReadPermissions(perms, OnLogin);
}
Then you can check to see if you got the e-mail address permission using
AccessToken token = AccessToken.CurrentAccessToken;
if (token.Permissions.Contains("email")) { // do something }
If you do, then you move forward with the Facebook share.

Google Sign-In with Passportjs not getting authenticated

I'm using Sails with Passport for authentication. I'm using passport-google-oauth(OAuth2Strategy) and passport-facebook for enabling Google Sign-in.
I'm not too well-versed with Passport, so pardon me if this is a rookie question. I've set up login via Facebook and it works just fine. With Google, I do receive an authorization code after allowing access to the app, but the I'm eventually not authenticated. I'm guessing the same code should work for both Facebook and Google since the strategies are both based on oauth2.
I'm not even sure what code to share, since I'm using the auto-generated code from sails-generate-auth, but do let me know if there's anything else I can share.
Any ideas on why this might be happening? The app is locally hosted but that's unlikely to be the problem since I am getting to the authorization stage anyway.
I faced the same problem and it was located here in in api/services/passport.js:
// If the profile object contains a list of emails, grab the first one and
// add it to the user.
if (profile.hasOwnProperty('emails')) {
user.email = profile.emails[0].value;
}
// If the profile object contains a username, add it to the user.
if (profile.hasOwnProperty('username')) {
user.username = profile.username;
}
// If neither an email or a username was available in the profile, we don't
// have a way of identifying the user in the future. Throw an error and let
// whoever's next in the line take care of it.
if (!user.username && !user.email) {
return next(new Error('Neither a username nor email was available'));
}
The Google service was not returning a profile.username property.
Because of it, the user is not saved in the database and cannot be authenticated. Then the passport callback receives an empty user, so the function that handles errors is fired and the user is redirected to the login page.
This change allows to use the displayName property as the username:
// If the profile object contains a list of emails, grab the first one and
// add it to the user.
if (profile.hasOwnProperty('emails')) {
user.email = profile.emails[0].value;
}
// If the profile object contains a username, add it to the user.
if (profile.hasOwnProperty('username')) {
user.username = profile.username;
}
/** Content not generated BEGIN */
// If the username property was empty and the profile object
// contains a property "displayName", add it to the user.
if (!user.username && profile.hasOwnProperty('displayName')) {
console.log(profile); // <= Use it to check the content given by Google about the user
user.username = profile.displayName;
}
/** Content not generated END */
// If neither an email or a username was available in the profile, we don't
// have a way of identifying the user in the future. Throw an error and let
// whoever's next in the line take care of it.
if (!user.username && !user.email) {
return next(new Error('Neither a username nor email was available'));
}
You could also use the profile.id property because profile.displayName is not necessarily unique (ie: two Google accounts can have an identical displayName). But it is also true accross different services: a Twitter account could also have the same username than a Facebook account. If both register on your application, you will have a bug. This is a problem from the code generated by sails-generate-auth and you should adapt it with the behavior that you want.
I will propose a PR if this solution works for you too.
Alright, so this ultimately turned out to be a known issue with the API.
TL;DR: Enable the Google+ API and the Contacts API as mentioned here. (The Contacts API isn't required, as #AlexisN-o pointed out in the comments. My setup worked as desired with Contacts API disabled. This obviously depends on what scope you're using.)
I believe it's not a nice way of failing since this was an API error that was prevented from bubbling up. Anyway, I dug into passport.authenticate to figure out what was going wrong. This eventually calls the authenticate method defined in the package corresponding to the strategy (oauth2 in this case). In here (passport-google-oauth/lib/passport-google-oauth/oauth2.js) I found that the accessToken was indeed being fetched from Google, so things should be working. This indicated that there was a problem with the requests being made to the token urls. So I ventured a little further into passport-oauth2/lib/strategy.js and finally managed to log this error:
{ [InternalOAuthError: failed to fetch user profile]
name: 'InternalOAuthError',
message: 'failed to fetch user profile',
oauthError:
{ statusCode: 403,
data: '{
"error": {
"errors": [{
"domain": "usageLimits",
"reason": "accessNotConfigured",
"message": "Access Not Configured. The API (Google+ API) is not enabled for your project. Please use the Google Developers Console to update your configuration.",
"extendedHelp": "https://console.developers.google.com"
}],
"code": 403,
"message": "Access Not Configured. The API (Google+ API) is not enabled for your project. Please use the Google Developers Console to update your configuration."
}
}'
} }
This was the end of the hunt for me and the first result for the error search led to the correct answer. Weird fix though.

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.

AgileToolkit OAuth add-on error 500 at facebook's mobile site

I am using the OAuth Facebook controller add-on for ATK4.
It works as expected when authenticating with Facebook from a regular desktop browser.
It works when authenticating using a mobile browser that is telling face book that it's a desktop browser.
It does not work when Facebook detects a mobile browser and redirects to m.facebook.com/dialog/oath.
What's more, is that it works fine for signups from mobile browsers (ie, when Facebook asks the user to give permission to the app).
The login flow stops with an Error 500 at:
https://m.facebook.com/dialog/oauth?redirect_uri={my_url_encoded_landing_page_where_the_OAuth_controller_lives}&scope=email&client_id={fb_app_id}
What the hell is going on here? There isn't some difference between the Facebook mobile service and the regular one that the addon isn't taking care of, or is there?
It must be something I'm doing wrong. In init() on the page that handles the FB, I am doing the following:
function init(){
parent::init();
$f = $this->add("oauth/Controller_OAuth_Facebook", array('sign_method'=>'PLAINTEXT'));
if ($fbtoken = $f->check()) {
$f->setSignatureInfo();
$f->setAuthToken($fbtoken["access_token"], $fbtoken["expires"]);
$s = $this->add("sni/Controller_SNI_Facebook");
$s->setOAuth($f);
// ...
// grab profile from SNI, database lookup, session stuff, etc
// ...
}
}
I've tried all three sign_methods, and tried leaving it alone, but that doesn't make much difference because the user is not making it back to the controller with an access token to use anyway.
I tried creating a new app with Facebook and I get the same issues with a basically vanilla configuration on that. I've only marked and specified the "Website with Facebook Login" site URL integration.
The image below was captured from Chrome after overriding the user agent to a mobile device to trigger the forward to facebook's mobile servers:
Screen shot of request
Facebook closed my bug report with them stating that it's not an issue since no one else is reporting the bug. I am removing the ATK4 tag, as I get the same issue using the example PHP code provided by Facebook on GIT.
Created dedicated example here:
http://demo.ambienttech.lv/d.html?ns=d3
Example is downloadable and includes instructions of setting up facebook app as well. See if that helps.
Try This:
<?php
class page_fb extends Page {
function init(){
parent::init();
$f = $this->add("oauth/Controller_OAuth_Facebook");
$fbtoken = $this->api->recall("fbtoken");
if ($m = $_GET["error_msg"]){
$v=$this->add("View_Error");
$v->add("Text")->setHTML("You can't connect to the application.");
$v->add("Button")->setHTML("Try again")->js("click", $this->js()->univ()->location("fb"));
return;
}
if (!$fbtoken){
if ($fbtoken = $f->check("email")){
$this->api->memorize("fbtoken", $fbtoken);
$this->api->redirect($this->api->url("/index"));
}
} else {
$f->setSignatureInfo();
$f->setAuthToken($fbtoken["access_token"], $fbtoken["expires"]);
$c = $this->add("sni/Controller_SNI_Facebook");
$c->setOAuth($f);
if (!$this->api->recall("fbuserinfo")){
$this->api->memorize("fbuserinfo", $c->getUserProfile());
}
$info = $this->api->recall("fbuserinfo");
$username = $info->username;
$img = $c->customRequest("/" . $username . "/picture?type=large");
$this->api->memorize("userimg", $img);
$this->api->memorize("userinfo", $info);
if (!$this->api->auth->isLoggedIn()){
$this->api->auth->login($info->email);
}
$this->api->redirect($this->api->url("/index"));
}
}
}
I've got the same problem, but using PHP: just using a mobile web browser is not working, giving '500 internal server error'.
I'm just asking myself if exists a parameter for the method getLoginUrl to force return a non-mobile version of the authentication page...
I reported this issue here: https://github.com/atk4/atk4-addons/issues/35
Please stay tuned and if you can, you can always make changes yourself and pull request.
I can't test and fix this because strangely I still don't have smart phone :(
Something changed in FB's mobile OAuth service that is causing the error. I ran a test with my code base on a shorter URL (ie; http://domain.net/fb/ rather than http://development.project.domain.net/fb) and it works fine. I am not entirely sure of what exactly is causing the problem as Facebook refuses to acknowledge the issue as being on their server, but I have a few possible culprits that may be triggering the error on their side, but since they don't care, I don't either, and I am providing my results for anyone else who encounters this bs.
The environment I am developing in uses semi-complex (apparently) naming scheme. The development server has its own hostname under a subdomain. The issue may be caused by the fact that there are multiple components to the host portion of the URL or simply too many characters.
The name servers for the development environment are provided by DynDNS. Facebook's mobile OAuth service may be choking on the idea of a development site being hosted on a non-permanent IP address.
I'm not going to do anymore testing on this because it really is a problem with Facebook, not my code or servers, and it will work in production.

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

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.