How to deal with Facebook API infamous "Session key invalid or no longer valid" error

While developing Facebook application I got stuck with "Session key invalid or no longer valid" error. Googling for it gave me lots of results, but not a single solution! So, after finally dealing with it, I decided to blog about it to help fellow Facebook developers and not to forget about the solution myself.

First of all, check out whether your app is authorized with Facebook by going to the following address in the browser window where you got the exception:

http://www.facebook.com/login.php?api_key=YOUR_APP_KEY&next=RETURN_URL

After that, you have to create Facebook API object to work with. Here's the example in C# (using .Net Facebook Developer Toolkit), principles for other platforms remain the same:


facebook.API api = new facebook.API();
api.ApplicationKey = "YOUR_APP_KEY";
api.Secret = "YOUR_SECRET_KEY";
api.SessionKey = HttpContext.Current.Request.Cookies["YOUR_APP_KEY" + "_session_key"].Value;
int userID = -1;
int.TryParse(HttpContext.Current.Request.Cookies["YOUR_APP_KEY" + "_user"), out userID);
api.uid = userID;



The key line of code here is the one when you're setting API session key. It is tempting (and natural!) to take the session key from request by using Request["fb_sig_session_key"], but for some mysterious reason this results in "Session key invalid or no longer valid" error. The only way to circumvent this ugly bug that I'm aware of is to take session key from cookie, not from request. That's it, after setting session key to "YOUR_APP_KEY_session_key" cookie I had no problems with this issue.
After that, just use the API object as usual. For example, in terms of .Net Facebook Developer Toolkit, use the following code to get a list your friends ids:


api.friends.get();

0 коментарі Посилання на цей допис

blog comments powered by Disqus