Authorization through facebook. An error occurred. Please try again later - facebook

In my app I authorization through facebook, all was ok. But now I try login through FB and get error: An error occurred. Please try again later. I update my Facebook, but It doesn't help
This is my code
private const string ExtendedPermissions = "user_about_me";
private FacebookClient _fb = new FacebookClient();
public MainPage()
{
InitializeComponent();
var parameters = new Dictionary<string, object>();
parameters["client_id"] = FacebookSettings.AppID;
parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
parameters["response_type"] = "token";
parameters["display"] = "page";
parameters["scope"] = ExtendedPermissions;
Uri ur = _fb.GetLoginUrl(parameters);
webBrowser1.Navigate(ur);
}
private void Browser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs l)
{
if (!_fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
{
return;
}
if (oauthResult.IsSuccess)
{
var accessToken = oauthResult.AccessToken;
LoginSucceded(accessToken);
}
else
{
MessageBox.Show(oauthResult.ErrorDescription);
}
}

Related

Getting page details from Facebook account using App Access Token

I am stuck into a problem for which I have not found any solution or documentation.
I am building an app using Facebook API in which user will create an app and will give their APP ID & APP SECRET to the application in order to create pages or post to pages.
Now the problem is they will only login into my application not in facebook nor login using FB.
I am getting APP ACCESS TOKEN from APP ID & APP SECRET.
Using https://graph.facebook.com/oauth/access_token?client_id=APP_ID&client_secret=APP_SECRET&grant_type=client_credentials
But how could i use it to get pages for that account or generate USER ACCESS TOKEN from it?
Please help me with your expert guidance.
Thanks.
You cannot create Apps nor Pages by using the Graph API! See https://developers.facebook.com/docs/graph-api/reference/v2.0/page
If you want to publish to a Page the logged-in User administrers, you can request the respective Page Access Token (with publish_actions and manage_pages permissions!) via
GET /me/accounts
See
https://developers.facebook.com/docs/graph-api/reference/v2.0/user/accounts/
https://developers.facebook.com/docs/facebook-login/access-tokens#pagetokens
first of create developer apps and get token give some permission
public ActionResult Index()
{
var url = "http://www.facebook.com/v2.0/dialog/oauth/?scope=user_friends,read_friendlists,read_stream,read_insights,manage_pages,user_checkins,user_photos,read_mailbox,manage_notifications,read_page_mailboxes,email,user_videos,user_groups,offline_access,publish_actions,manage_pages&client_id=" + ConfigurationManager.AppSettings["ClientId"] + "&redirect_uri=" + ConfigurationManager.AppSettings["RedirectUrl"] + "&response_type=code";
return Redirect(url);
}
that automatic redirect call back url for example
public ActionResult AddFacebookAccount(string code)
{
string ret = string.Empty;
string client_id = ConfigurationManager.AppSettings["ClientId"];
string redirect_uri = ConfigurationManager.AppSettings["RedirectUrl"];
string client_secret = ConfigurationManager.AppSettings["ClientSecretKey"];
long friendscount = 0;
try
{
FacebookClient fb = new FacebookClient();
string profileId = string.Empty;
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("client_id", client_id);
parameters.Add("redirect_uri", redirect_uri);
parameters.Add("client_secret", client_secret);
parameters.Add("code", code);
JsonObject fbaccess_token = null;
try
{
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
fbaccess_token = (JsonObject)fb.Get("/oauth/access_token", parameters);
}
catch (Exception ex)
{
try
{
fbaccess_token = (JsonObject)fb.Get("/oauth/access_token", parameters);
}
catch (Exception ex1)
{
ViewBag.acc_tkn= "issue_access_token";
}
}
string accessToken = fbaccess_token["access_token"].ToString();
Session["AccessToken"] = accessToken;
if (accessToken != null)
{
fb.AccessToken = accessToken;
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
dynamic profile = fb.Get("v2.2/me");
dynamic friends = fb.Get("v2.2/me/friends");
try
{
Session["uid"] = profile.id;
friendscount = Convert.ToInt16(friends["summary"]["total_count"].ToString());
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
ViewBag.acc_tkn = accessToken;
ViewBag.Uid = profile.id;
}
return View();
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
ViewBag.acc_tkn= "Something Went Wrong";
return View();
}
}
you will get access Token when post data on page refer Bellow Code
public void FacebookPostonPage(string file, string message, string tokenid)
{
JsonObject fbaccess_token = null;
FacebookClient fb = new FacebookClient();
fb.AccessToken = tokenid;
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
fbaccess_token = (JsonObject)fb.Get("v2.0/me/accounts");
dynamic Result = fbaccess_token["data"];
foreach (var obj in Result)
{
string result = FacebookComposeMessage(obj.access_token, obj.id, message, file);
}
}
public string FacebookComposeMessage(string tokenid,string userid ,String message,string imagepath)
{
FacebookClient fb = new FacebookClient();
string ret = "";
fb.AccessToken = tokenid;
fb.AppId = ConfigurationManager.AppSettings["ClientId"];
fb.AppSecret = ConfigurationManager.AppSettings["ClientSecretKey"];
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
var args = new Dictionary<string, object>();
args["message"] = message;
if (!string.IsNullOrEmpty(imagepath))
{
var media = new FacebookMediaObject
{
FileName = "filename",
ContentType = "image/jpeg"
};
byte[] img = System.IO.File.ReadAllBytes(imagepath);
media.SetValue(img);
args["source"] = media;
ret = fb.Post("v2.0/" + userid + "/photos", args).ToString();
}
else
{
ret = fb.Post("v2.0/" + userid + "/feed", args).ToString();
// ret = fb.Post("/" + objFacebookAccount.FbUserId + "/photos", args).ToString();
// var data = fb.Get("v2.2" + ret);
}
return ret;
}
You will post Successfully try now

Error using facebook C# sdk with WPF web browser

I am new to facebook c# sdk. I followed the tutorial in this link.
I created an application that displays the user name after log in. Here is my code:
public partial class MainWindow : Window
{
private string appId = "appid";
private string extenededPermissions = "offline_access,publish_stream";
private Uri loginUrl = null;
private string accessToken = null;
private string userName = null;
public MainWindow()
{
InitializeComponent();
}
/// <summary>
/// Function to get the login url
/// with the requested permissions
/// </summary>
private void GetLoginUrl()
{
dynamic parameters = new ExpandoObject();
// add the client id
parameters.client_id = appId;
// add the redirect uri
parameters.redirect_uri = "https://www.facebook.com/connect/login_success.html";
// requested response
parameters.response_type = "token";
// type of display
parameters.display = "popup";
// If extended permissions are present
if (!string.IsNullOrWhiteSpace(extenededPermissions))
parameters.scope = extenededPermissions;
// Create the login url
Facebook fc = new FacebookClient();
loginUrl = fc.GetLoginUrl(parameters);
}
private void WindowLoaded(object sender, RoutedEventArgs e)
{
// get the login url
GetLoginUrl();
// Navigate to that page
webBrowser.Navigate(loginUrl);
}
private void webBrowser_Navigated(object sender, NavigationEventArgs e)
{
var fc = new FacebookClient();
FacebookOAuthResult fr;
// Check the returned url
if (fc.TryParseOAuthCallbackUrl(e.Uri, out fr))
{
// check if authentication is success or not
if (fr.IsSuccess)
{
getUserName(out userName);
}
else
{
var errorDes = fr.ErrorDescription;
var errorReason = fr.ErrorReason;
}
}
else
{
}
}
private void getUserName(out string name)
{
var fb = new FacebookClient(accessToken);
// Get the user details
dynamic result = fb.Get("me");
// Get the user name
name = result.name;
MessageBox.Show("Hai " + name + ",Welcome to my App");
}
}
My Problem is with the FacebookOAuthResult.
private void webBrowser_Navigated(object sender, NavigationEventArgs e)
{
var fc = new FacebookClient();
FacebookOAuthResult fr;
// Check the returned url
if (fc.TryParseOAuthCallbackUrl(e.Uri, out fr))
{
// check if authentication is success or not
if (fr.IsSuccess)
{
getUserName(out userName);
}
else
{
var errorDes = fr.ErrorDescription;
var errorReason = fr.ErrorReason;
}
}
else
{
}
}
After I logged in it is redirecting to redirect_uri. But the fc.TryParseOAuthCallbackUrl(e.Uri, out fr) fails though the webbrowser redirects to the Authentication successful page.
So I couldn't get the access token. What could the problem in my code be?
This doesn't answer the question, but I see you are asking for an offline_access permission. Facebook removed offline_access sometime ago. Instead you need an Extended Access Token. You get it by exchanging the access token you are trying to get, for an extended one. They last for about 2-3 months after which you have to get a new one.
Nevermind i have found out the solution..Thanks to the answers for the question!
I have added the Winforms web browser control to the wpf and the authentication is working.The problem is with WPF web browser. It simply omits the url after # token So the parseurl won't able to authenticate it.
Here's the modified code..
private void WindowLoaded(object sender, RoutedEventArgs e)
{
// create the windows form host
System.Windows.Forms.Integration.WindowsFormsHost sample =
new System.Windows.Forms.Integration.WindowsFormsHost();
// create a new web browser
webBrowser = new System.Windows.Forms.WebBrowser();
// add it to winforms
sample.Child = webBrowser;
// add it to wpf
canvas1.Children.Add(sample);
webBrowser.Navigated += webBrowser_Navigated;
webBrowser.Navigate(loginURL);
}
void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
// do the authentication
var fc = new FacebookClient();
FacebookOAuthResult fr;
// Check the returned url
if (fc.TryParseOAuthCallbackUrl(e.Url, out fr))
{
// check if authentication is success or not
if (fr.IsSuccess)
{
accessToken = fr.AccessToken;
// Actions to do
}
else
{
var errordes = fr.ErrorDescription;
var errorreason = fr.ErrorReason;
}
}
else
{
//Not a valid url
}
}
The problem is solved!!

How can I change the user while using the Facebook C# sdk on Windows Phone?

I've started using the C# facebook sdk in my WP7 app, and it works, but I can only log in once. I have a class that opens a web browser and loads a facebook login page. I type in my info, and it does what I want it to do. But once I try to log in again, it remembers the info I gave it earlier, and I can't test other facebook accounts. Does anyone know how to clear my old data so I can log in with another account?
You need to perform Logout operation for performing login operation with another account try this code for performing logout.
public partial class LogoutPage : PhoneApplicationPage
{
private Uri navigateUrl;
public FacebookOAuthResult FacebookOAuthResult { get; private set; }
public LogoutPage()
{
var appId = "173963872698818";
string[] extendedPermissions = new[] { "user_about_me", "offline_access" };
var oauth = new FacebookOAuthClient { AppId = appId };
var parameters = new Dictionary<string, object>
{
{ "response_type", "token" },
{ "display", "wap" } //"popup works, touch not works
};
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
parameters["scope"] = scope.ToString();
}
var loginUrl = oauth.GetLoginUrl(parameters);
var logoutParameters = new Dictionary<string, object>
{
{ "next", loginUrl }
};
//Redirect to the following url.
// https://www.facebook.com/logout.php?next=YOUR_URL&access_token=ACCESS_TOKEN
//this.navigateUrl = oauth.GetLogoutUrl(logoutParameters);
var a = App.Current as App;
string absoluteURI = " https://www.facebook.com/logout.php?next=http://www.fengshuiexplorer.host56.com&access_token=" + a.myToken;
this.navigateUrl = new Uri(absoluteURI);
InitializeComponent();
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
webBrowser1.Navigate(this.navigateUrl);
}
private void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult result;
if (FacebookOAuthResult.TryParse(e.Uri, out result))
{
this.FacebookOAuthResult = result;
var a = App.Current as App;
a.isLoggedIn = false;
NavigationService.GoBack();
}
else
{
this.FacebookOAuthResult = null;
}
}
}
Or you could try to call below code snippets before you log in again.
await new WebBrowser().ClearCookiesAsync();

How to logout FaceBook in window phone 7

I have a problem logging out of Facebook on Windows Phone. I have the code to login, but I can't log out of it. Can someone show me how to log out of Facebook on a Windows Phone?
Here's the login code:
private FacebookClient _asyncFbClient;
private string _appID = "";
private string _appSecret = "";
private void StartFacebookLogin(object sender, RoutedEventArgs e)
{
string[] extendedPermissions = new[] { "user_about_me", "publish_stream", "email" };
FacebookClient fb = new FacebookClient();
var oauth = new FacebookOAuthClient { AppId = _appID, AppSecret = _appSecret };
var logout = new FacebookUser();
var parameters = new Dictionary<string, object>
{
{"response_type", "token"},
{"display", "touch"}
};
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
parameters["scope"] = scope.ToString();
}
var loginUrl = oauth.GetLoginUrl(parameters);
webBrowser.Navigated += new EventHandler<System.Windows.Navigation.NavigationEventArgs>(CheckForAuth);
webBrowser.Navigate(loginUrl);
}
private void CheckForAuth(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult result;
if (FacebookOAuthResult.TryParse(e.Uri, out result))
{
if (result.IsSuccess)
{
IsolatedStorageSettings Settings = IsolatedStorageSettings.ApplicationSettings;
MessageBox.Show(result.AccessToken);
access = result.AccessToken;
if (Settings.Contains("MyFacebookAccessToken1"))
Settings["MyFacebookAccessToken1"] = result.AccessToken;
else
Settings.Add("MyFacebookAccessToken1", result.AccessToken);
Settings.Save();
_asyncFbClient = new FacebookClient(result.AccessToken);
_asyncFbClient.GetCompleted += new EventHandler<FacebookApiEventArgs>(_asyncFbClient_GetCompleted);
_asyncFbClient.GetAsync("/me");
}
}
}
Here's the logout code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(linkUrl);
request.Method = "GET";
request.BeginGetResponse(new AsyncCallback(LogoutResponse), request);
private void LogoutResponse(IAsyncResult result)
{
string responseData = "";
try
{
HttpWebRequest request = result.AsyncState as HttpWebRequest;
HttpWebResponse response = request.EndGetResponse(result) as HttpWebResponse;
if (response != null && response.StatusCode == HttpStatusCode.OK)
{
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
responseData = reader.ReadToEnd();
//responseData = true
}
}
catch (Exception ex)
{
Dispatcher.BeginInvoke(() => { MessageBox.Show(ex.Message); });
}
}
I have tried to use Facebook's logout API and get a successful result, but the next time I open the web browser it's already automatically logged in to Facebook again. How can I get it to log out?
I tried quite a few hacks to get this to work... and then Facebook finally updated their documentation with a good answer:
Logout
You can log a user out of their Facebook session by directing them to
the following URL:
https://www.facebook.com/logout.php?next=YOUR_URL&access_token=ACCESS_TOKEN
YOUR_URL must be a URL in your site domain, as defined in the
Developer App.
From http://developers.facebook.com/docs/authentication/
there is no FB Logout, it has been removed.
your best bet is to forget your credentials.
Facebook PHP SDK uses a function like this:
public function getLogoutUrl($params=array()) {
return $this->getUrl(
'www',
'logout.php',
array_merge(array(
'next' => $this->getCurrentUrl(),
'access_token' => $this->getAccessToken(),
), $params)
);
}
Which creates a URL like:
https://www.facebook.com/logout.php?next={YOUR_ENCODED_URL}&access_token={YOUR_ACCESS_TOKEN}
I believe the encoded URL must be owned by the application to whom the access_token belongs.
If you get that URL right, it'll work (just tried for one of my applications).
I'm not 100% sure if it works on windows-phone, but you can give it a try.

How Can I post a status update to facebook from my WP7 App?

Hi Im writing an app that allows users to post status updates from within the application, I believe that ive got the authentication working correctly for the login, I just dont know how to go about posting a status update. Any code/examples/tutorials of how to go about doing this would be fantastic, here is the code that I have so far for the authentication.
public partial class FacebookAuth : PhoneApplicationPage
{
private string _accessToken;
private WebBrowser _webBrowser;
public FacebookAuth()
{
InitializeComponent();
_webBrowser = new WebBrowser();
this.Loaded += new RoutedEventHandler(FacebookAuthPage_Loaded);
}
void FacebookAuthPage_Loaded(object sender, RoutedEventArgs e)
{
//Get this from the facebook
string appId = "XXXXXXXXXXXXXXX";
string[] extendedPermissions = new[] { "publish_stream", "offline_access", "user_groups" };
var oauth = new FacebookOAuthClient { AppId = appId };
//Telling the Facebook that we want token as response
//and we are using touch enabled device
var parameters = new Dictionary<string, object>
{
{ "response_type", "token" },
{ "display", "touch" }
};
//If there's extended permissions build the string and set it up
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
parameters["scope"] = scope.ToString();
}
//Create the login url
var loginUrl = oauth.GetLoginUrl(parameters);
//Add webBrowser to the contentPanel
ContentPanel.Children.Add(_webBrowser);
_webBrowser.Navigated += webBrowser_Navigated;
//Open the facebook login page into the browser
_webBrowser.Navigate(loginUrl);
}
void webBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult result;
//Try because there might be cases when user input wrong password
if (FacebookOAuthResult.TryParse(e.Uri.AbsoluteUri, out result))
{
if (result.IsSuccess)
{
_accessToken = result.AccessToken;
MessageBox.Show(_accessToken);
//Hide the browser controller
_webBrowser.Visibility = System.Windows.Visibility.Collapsed;
}
else
{
var errorDescription = result.ErrorDescription;
var errorReason = result.ErrorReason;
MessageBox.Show(errorReason + " " + errorDescription);
}
}
}
private void PostBtn_Click(object sender, RoutedEventArgs e)
{
}
}
}
To publish a status, do an HTTP Post to /me/feed with a post parameter called "message" and it's value being what the authenticate user posted.
Using FacebookClient
var client = new FacebookClient(user_access_token);
dynamic parameters = new ExpandoObject();
parameters.message = "Hello World!"
dynamic post_id = client.Post("/me/feed", parameters);
See also: http://blog.prabir.me/post/Facebook-CSharp-SDK-Making-Requests.aspx