Parse Unity Facebook 400 Bad Request - facebook

I am using the Facebook SDK and Parse plugin. I can sucessfully login with Parse and Facebook independently. When I try to 'sign up' for parse using my Facebook access token I get a 400 bad request.
I believe my parse.com account is setup correctly (I have augmented the authentication section with my application ID(s) and secret(s) (for main app and test app).
Here is my code.
// FB Init and Login here. It works.
var logInTask = ParseFacebookUtils.LogInAsync(FB.UserId, FB.AccessToken, DateTime.UtcNow.AddDays(1));
while (!logInTask.IsCompleted)
{
yield return 1;
}
if (logInTask.IsCanceled || logInTask.IsFaulted)
{
var error = logInTask.Exception as AggregateException;
foreach (var e in error.InnerExceptions)
{
// Bad Request Here
Debug.LogError(e);
}
}
What am I doing wrong, how can I resolve this ?

I suspect the issue here is that you're passing in a DateTime object for token expiration, when you should be passing in the expires_at value that came back with your Facebook login. I believe this is an integer.

Related

Check Facebook login status using Alloy or Titanium in an iOS app

I want to add Facebook login to my Alloy/ Titanium ios app.
So far I have the following code:
var fb = require('facebook');
fb.initialize();
fb.setLoginBehavior(fb.LOGIN_BEHAVIOR_NATIVE);
fb.permissions = ['email', 'public_profile'];
function doFacebookLogin() {
// occurs when a button is clicked
if (fb.loggedIn) {
facebookLogin(fb);
} else {
fb.authorize();
}
}
fb.addEventListener('login', function(event) {
if (event.success) {
facebookLogin(fb);
}
});
function facebookLogin(fb) {
Ti.API.info(fb.accessToken);
// send the fb.accessToken server-side and register & login the user
}
For the most part the code works fine!
The issue is when the user de-authorises the app, fb.login still return true and so is using the same access token.
How can I check if the user has de-authorised my app. I know it's easily possible using the JavaScript SDK using FB.getLoginStatus: https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus , but I can't find an equivalent in Alloy/Titanium: https://docs.appcelerator.com/platform/latest/#!/api/Modules.Facebook
You need to call fb.logout() to set fb.loggedIn to false.
fb.logout clears the access token and resets the login state to false.
Note: I am not sure whether clearing the access token in Titanium module will also clear the token on FB server. So even after calling fb.logout(), you might receive the same access token if and only if it has not expired on fb server.
Read more about Facebook Access Token here

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.

FacebookAuthorizeFilter endless redirect

I'm trying to add facebook login to my application. To that extent I'm using a following snippet of code:
[FacebookAuthorize]
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
And I register a filter FacebookAuthorizeFilter.
When I navigate to /Home/About what I get is an endless redirect to
/Home/About?code=AQAPoxl1J-.......
I can login using facebook if I just use OAuth provided in ASP.NET MVC4 project template.
What am I missing?
I delved into the FacebookAuthorize filter code more. The reason the Filter does not work with non-canvas applications is that inside the filter's OnAuthorization method the the method is relying on Facebook's signed_request being present in the POST requset when the user is redirected back to your application. If signed_request is never present the filter will continue to redirect:
...code omitted...
if (signedRequest == null || String.IsNullOrEmpty(userId) || String.IsNullOrEmpty(accessToken))
{
// Cannot obtain user information from signed_request, redirect to Facebook OAuth dialog.
string redirectUrl = GetRedirectUrl(request);
Uri loginUrl = client.GetLoginUrl(redirectUrl, _config.AppId, null);
filterContext.Result = CreateRedirectResult(loginUrl);
}
...code omitted..
An alternative approach may be to create a similar filter that checks for the existent of the code query string parameter. Once code is obtained you may use your application's appId and appSecret to exchange the code for an access token. Once the access token is obtained you may determine which permissions the user has granted and process appropriately.
After hours spent debugging, reflecting, source-code analyzing I came to the conclusion that FacebookAuthorizeAttribute and FacebookAuthorizeFilter can only meaningfully be used in a Facebook Canvas application.

Do not receive a response from FBAS.init

It was working till Thursday of last week, but I'm wondering if something changed cause the code has been the same since then.
I pass the following JSON information to the FBAS.init call from my app in facebook
{"oauth":true,"appId":"MYAPPID"}
Here's the relevant code:
//We call Facebook API init call like so:
trace("init");
Facebook.init(_appKey, _fbInitResponse);
//Here's our callback
protected function _fbInitResponse(success:Object, fail:Object):void
{
trace("fbInitResponse: success = " + success);
// User logged in successfully
if (success)
{
trace("\t session recieved!");
_session = success;
dispatchEvent(new Event(FacebookEvent.INIT));
}
else
{
trace("ERROR: " + fail);
}
}
Actually: It looks like a bug with Facebook not redirecting to the Secure Canvas URL properly. The hack below is a short-term work-around, but this looks like a bug on Facebooks end.
Ran into the same problem as you. Was a mismatch when a user was using https to access the Facebook app, but the app page was being served in http.
A Facebook auth change has been propagating to users since March.
I assume this was the change to cause the bustage:
https://developers.facebook.com/roadmap/#enhanced-auth-dialog
The tip found in this answer helped me:
Facebook JavaScript SDK over HTTPS loading non-secure items
I put the: FB._https = (window.location.protocol == "https:");
I put it right after the fb-root div in a script element. Very hacky.

How to retrieve the facebook oauth 2.0 access_token

I am trying to get the access_token of the logged in facebook user.
I get something like this.. url followed by the code i am retrieve the code..
it says in the guide to exchange it for access_token...
https://graph.facebook.com/oauth/access_token?
client_id=XXXXXXXXXXXXXX&
redirect_uri=http://www.my-site.com/&
client_secret=XXXXXXXXXXXXXXXXXXXXX&
code=2.hJFWoMlLf3tLOSos_qNCBg__.3600.1279836000-10000100XXXXXXX|kGwPB4y5K_-ijD9_1CfjSpT-oaY..
How i can exchange it for a access_token using what FB.api or jquery or javascript..
When i plug this url in the address bar.. i am able to see access_token..
I appreciate if somebody can tell me how to retrieve the access_token using javascript or jquery.
Thanks.
According to Facebook, and my personal experiences with the api, the FB.getSession() function is deprecated and should throw an exception if called.
From facebook:
The FB.getAuthResponse method is a replacement for the FB.getSession method which was deprecated after the migration to OAuth 2.0.
Instead you should use the getLoginStatus callback -
FB.getLoginStatus(function(response) {
var token = response.authResponse.accessToken;
});
//Example structure of response object
var eg =
{
status: 'connected',
authResponse: {
accessToken: '...',
expiresIn:'...',
signedRequest:'...',
userID:'...'
}
};
source: http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
If you are using the JavaScript SDK, then after logging in the user, getting the access token in your JavaScript code is as simple as:
FB.getSession().access_token
However, getSession may return null if a user is logged out, so the proper way is to first check for null before accessing the token.
var session = FB.getSession();
if(session != null) { // user is still logged in
console.log(session.access_token);
}