facebook graph api request fail - facebook

Hi I am using the facebook graph api in an android project and the project crashed today for no reason, after debugging the code I found that the request to the facebook graph api fail
here is my Kotlin code :
var graphRequest = GraphRequest(AccessToken.getCurrentAccessToken(), "/{${AccessToken.getCurrentAccessToken().userId}}/albums", null, HttpMethod.GET, object : GraphRequest.Callback {
override fun onCompleted(response: GraphResponse?) {
if (response != null) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
}).executeAsync()
I tried the request using the Graph API explorer to make sure that the code isn't the issue and it failed also:
click to see the screenshot
I hope you can figure what is the real problem as I'm new to the api, thank you in advance.

Related

Facebook OAuth stopped working suddenly

I noticed yesterday that my Facebook login for my website has stopped working.
This has been working great for the last 2 months, as far as I am aware I have not changed anything. I have tried everything I can on links such as: - as well as many more...
ASP.NET MVC5 OWIN Facebook authentication suddenly not working
I have noticed that the Stack Overflow Facebook auth has also stopped working.
Has anyone else noticed this and found any solution? It's worth noting I am using azure app services to host. But this issue is also found when I am using localhost.
My current setup looks like this...
in Startup.Auth.cs
var facebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions()
{
AppId = "xxxxxxxxxxxxx",
AppSecret = "xxxxxxxxxxxx"
};
facebookOptions.Scope.Add("email");
app.UseFacebookAuthentication(facebookOptions);
In the following method, loginInfo is null every time.
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
I also added a session "WAKEUP" from a different post suggestion, fb auth failed once before and this fixed the issue this time, but it has come back.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
Session["WAKEUP"] = "NOW!";
// Request a redirect to the external login provider
return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}
As RockSheep explained. Facebook dropped the support vor API v2.2. You need to update your OWIN nuget packages.
You can find the issue on github (from the Katanaproject).
Ensure to activate pre releases in your nuget manager, than you are able to update the nuget packages to version v3.1.0-rc1. But beware: After the update, you need to test your login carefully (maybe you also have other authentication providers like Microsoft or Google, you should test them as well).
Technical
The Api changed the version number to v2.8 and the return value from the API is now in JSON-Format and no longer escaped in the URI. The 'old' OWIN packages can not handle this changes.
[Oauth Access Token] Format - The response format of
https://www.facebook.com/v2.3/oauth/access_token returned when you
exchange a code for an access_token now return valid JSON instead of
being URL encoded. The new format of this response is {"access_token":
{TOKEN}, "token_type":{TYPE}, "expires_in":{TIME}}. We made this
update to be compliant with section 5.1 of RFC 6749.
Here you can find the code-changes on GitHub for further informations and better understanding.
A lot of people started having trouble after yesterday. This is due to Facebook dropping support for v2.2 of their API. For some reason their system still redirects auth calls that don't use a version number to the 2.2 API. A quickfix is to ensure that the API version gets sent with the API call.
Starting at v2.3 Facebook also started returning JSON objects. So make sure to change that in the code as well.
I had the same issue, found solution here Fix facebook oauth 2017
Basically, you need to extend HttpClientHandler and decode JSON response instead of body
Here is a solution for those who are using scribe java.
public Token extract(String response)
{
Preconditions.checkEmptyString(response, "Response body is incorrect. Can't extract a token from an empty string");
JSONObject obj = new JSONObject(response);
return new Token(obj.get("access_token").toString(), EMPTY_SECRET, response);
}
Create a new class and set the extractor to JSON.
import org.scribe.builder.api.DefaultApi20;
import org.scribe.extractors.AccessTokenExtractor;
import org.scribe.extractors.JsonTokenExtractor;
import org.scribe.model.OAuthConfig;
public class FaceFmApi extends DefaultApi20 {
#Override
public String getAccessTokenEndpoint()
{
return "https://graph.facebook.com/oauth/access_token";
}
#Override
public AccessTokenExtractor getAccessTokenExtractor()
{
return new JsonTokenExtractor();
}
#Override
public String getAuthorizationUrl(OAuthConfig config) {
return null;
}
}
and inject your newly created class as below. Then getAccessToken() will work as expected.
public OAuthService getService() {
return new ServiceBuilder().provider(FaceFmApi.class)
.apiKey(config.getApiKey()).apiSecret(config.getApiSecret())
.callback(config.getCallback()).build();
}

Parse Unity Facebook 400 Bad Request

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.

c# post photo on facebook without using c# sdk

please provide me a simple piece of code in c# to post photo on facebook without using the very famous facebook sdk for c#, as per my knowledge there are two methods of posting photos,
METHOD 1:
The fb documentation below shows a method to post image with the url provided,
https://developers.facebook.com/blog/post/526/?ref=nf
of course I tried, it does not seem to accept my image url, when I tried debugging here on facebook API explorer using the post method and entered the parameters as below,
SomeAlbumID/photos?=access_token=MyTOKEN&url=http%3a%2f%2fcutree.com%2fcutreefbapp%2fimg1.bmp&message=Family+Tree
It returns an exception saying
{
"error": {
"message": "http\u00253a\u00252f\u00252fcutree.com\u00252fcutreefbapp\u00252fimg1.bmp is an internal url, but this is an external request.",
"type": "CurlUrlInvalidException"
}
}
"internal url, but this is an external request." I am not sure what this means as I am using the same domain as registered on my fbapp, and also giving the request from the server itself.
I have read some where that fb accepts images from only a few servers, can anyone help me out.
METHOD 2:
This is a method where image data in bytes are atttached with the Post body as fb says "To publish a photo, issue a POST request with the photo file attachment as multipart/form-data."
However everyone does that using the fb sdk for c#, can anyone provide simple http post method for this issue.
I have tried streaming image data using a method below
public MyFacebookClass FBPost(string URI, string Parameters)
{
System.Net.WebRequest req = System.Net.WebRequest.Create("https://graph.facebook.com/" + URI);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = BmpToBytes_Serialization(new Bitmap("C:\\Users\\atul\\cutreefbapp\\DefaultThumb.bmp"));
req.ContentLength = bytes.Length;
System.IO.Stream os = req.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();
System.Net.WebResponse resp = req.GetResponse();
if (resp == null) return null;
System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
return new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<MyFacebookClass>(sr.ReadToEnd().Trim());
}
Posting photos by giving a parameter url definitively works. If it doesn’t for you, then you are doing something wrong.
(I just tried it with the URL of your picture on the Graph API Explorer, and it work as I expected it.)
when I tried debugging here on facebook API explorer using the post method and entered the parameters as below,
SomeAlbumID/photos?=access_token=MyTOKEN&url=http%3a%2f%2fcutree.com%2fcutreefbapp%2fimg1.bmp&message=Family+Tree
If that’s the actual address you tried to post to, then the = between photos? and access_token is clearly wrong.
The problem you have is your code isn't correct. In order to post a photo to Facebook you'll need to use a multi-part form data post. I haven't used the C# SDK, but I'm sure it builds a multi-part form post internally before submitting the image.
You will have to do something similar to what is posted here. I was about to post my code that does this exactly for Facebook from my app, but it is a bit long.

Facebook C# SDK Canvas Authorization

I have an iFrame Facebook application. I am using the Facebook C# SDK (version 6.0.10.0), Facebook and Facebook.Web (version 5.4.1.0') libraries.
As i get some help from stackoverflow and some other sites
Facebook C# SDK Authorization Problem
http://forum.ngnrs.com/index.php/topic,199.0.html
i coded as
protected void Page_Load(object sender, EventArgs e)
{
fbApp = new FacebookApp();
authorizer = new CanvasAuthorizer(fbApp);
authorizer.Perms = requiredAppPermissions;
if (authorizer.Authorize())
{
//user authorized
}
else
{
//user not authorized
}
}
but in the line "authorizer = new CanvasAuthorizer(fbApp);" it gives ma a syntax error
as Error 14 The best overloaded method match for 'Facebook.Web.CanvasAuthorizer.CanvasAuthorizer(Facebook.Web.FacebookWebContext)' has some invalid arguments.
In Facebook C# SDK there is no clue about the syntax change;
Please help ?
For a Canvas app, Facebook does a post request to your Canvas Url that you specified in your Application settings. In the post request, you get the signed_request parameter. All you have to do is parse that parameter using the Facebook API method and it will give you the access token which is used to make further calls.
Here is a brief tutorial about the same. This was written with ASP.NET MVC 3.0 in mind. However you can use most of the code for classic ASP.NET too.
http://theocdcoder.com/tutorialcreate-a-facebook-canvas-app-using-asp-net-mvc-3/

Titanium.Facebook getting graph api access token

I'm developing an iPhone app with Appcelerator Titanium SDK 1.6.2
I am upload an photo to a users facebook album with the Titanium Facebook module, graph api.
The upload goes just fine and returns the items unique ID.
When I try to parse the JSON from the unique id I'm told i need to pass an access token, which makes sense.
How do I get the access token to be passed to the graph request url?
When I do a XHR GET request while passing Ti.Facebook.accessToken I get the following error
URL: https://graph.facebook.com/10150527948301195?access_token=t4CqzHallahfy4d7RnERrJb4ffOkQfJvrYrGEBoZ4so.epdiI6IjJGR2ZFY1ZTMHh6RlR6ZmNIcVctMHcifQ.NBRMth0vb7pXKcd8lHNz9aremoyNpvrbhz2P3zkgWJU4eHdfewOp1WruBNZS_lSDy0XM0Xu0ACry8aEmSckGJVQJxEioykrNZhT7S9mJG2OKWqMdk6ucg5IMhXMfndF9sdKwWrWb7uPKI57LzIOf5lvA
{
error = {
message = "Unsupported post request.";
type = GraphMethodException;
};
}
And if I don't pass Ti.Facebook.accessToken I'm asked for it.
I'm bound to be missing something, any help would be greatly appreciated.
see this link http://developer.appcelerator.com/blog/2011/02/facebook-module-changes-in-titanium-mobile-1-6-0.html
I think you should be using Titanium.Facebook.requestWithGraphPath(...)