Facebook re-authentication in a popup window - c#

I write a windows forms application that connects to user's profile in facebook, reads his wall and shows him updates in a widget, with the help of facebook c# sdk.
Everything works fine, except for the fact that facebook won't let my user change his credentials, that means re-login as a different user.
My authentication flow is schematically as follows:
In login process initializer:
note: The dialog is shown in a popup. If you show dialog in a full
browser, it's possible to logout, but in popup this functionality
seems to be lacking.
private void loginButton_Click(object sender, EventArgs e){
browser = new WebBrowser();
this.browser.Navigated += new WebBrowserNavigatedEventHandler(browser_Navigated);
//+ all types of gui settings for the borwser
form.Controls.Add(browser);
Uri url=new Uri("https://www.facebook.com/dialog/oauth?client_id=" + {*MyAppsId*}+
"&redirect_uri=" + "https://www.facebook.com/connect/login_success.html" +
"&response_type=token"+
"&auth_type=reauthenticate"+
"&display=popup"+
"&scope=read_stream"
browser.Navigate(url);// +try/catches - omitted
}
Navigation response parsing:
note: just parsing the response with the use of c# sdk classes FacebookOAuthResult and FacebookClient
private void browser_Navigated(object sender, WebBrowserNavigatedEventArgs e){
FacebookOAuthResult oauthResult; //helps to streamline parsing
if (fb.TryParseOAuthCallbackUrl(e.Url, out oauthResult)){ //type of fb is FacebookClient of c# sdk
if (oauthResult.IsSuccess){
accessToken = oauthResult.AccessToken;
//from here start reaing user's feed with the help of access token
}
}
}
What i meant to do by it is that when the login button is clicked, the user is prompted his username and password.
However, the user is prompted to re-enter his password only, not to re-enter his username.
If I use the url without the "&auth_type=reauthenticate" parameter , it doesn't prompt for anything and straight sends me the access token.
How can I force the facebook to ask for a username?

After days of fighting, the answer was under my nose.
You just need to call https://www.facebook.com/logout.php with your access token:
WebBrowser browser = new WebBrowser();
browser.Navigated += browser_NavigatedLogout;
string logoutUrl = "https://www.facebook.com/logout.php?" +
"next=https://www.facebook.com/connect/login_success.html" +
"&access_token=" + MyAccessToken;
try
{
browser.Navigate(new Uri(logoutUrl));
}
catch (System.Exception other)
{
MessageBox.Show("error logging out: "+other.Message);
}
and the handler is:
private void browser_NavigatedLogout(object sender, WebBrowserNavigatedEventArgs e)
{
if (e.Url.AbsoluteUri == "https://www.facebook.com/connect/login_success.html")
{
//here anything you need to do after the user logged off
}
}

Related

How to redirect to another page after Google Login?

I am using google login as my SSO but when i successfully login with Google it redirect me back to my login page how can i redirect it to my homepage after login using Google login?
if (!string.IsNullOrEmpty(Request.QueryString["code"]))
{
string code = Request.QueryString["code"];
string json = GoogleConnect.Fetch("me", code);
GoogleProfile profile = new JavaScriptSerializer().Deserialize<GoogleProfile>(json);
Label1.Text = profile.Id;
Label2.Text = profile.DisplayName.ToString();
Label3.Text = profile.Emails.Find(email => email.Type == "account").Value;
Image1.ImageUrl = profile.Image.Url;
ImageButton1.Visible = false;
}
if (Request.QueryString["error"] == "access_denied")
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('Access denied.')", true);
}
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
GoogleConnect.Authorize("profile", "email");
}
you need to pass a callback url in google authentication api. After callback the provided url will called and method defined is this will be executed. In that method you will get user information and token to validate. After that you can redirect to your home page.
google callback give you success or error message. if you got success flag you get an array with user data. with those data you need to set an session. so you wont go back to your login page. or else when you call google api you haven't set proper call back for your application.

asp.net webforms google login

I have been searching the net for a solution to use a users google account for authentications on a asp.net webform application.
All I want is that the user login to his google account and return to my webform application with display name, google ID and Email form there I will take care of the rest.
I have tried http://dotnetopenauth.net/, Google .Net Api but I never found a working example.
Can anybody point me in the right direction with a example that works. (C# or vb.net)
Have you thought about giving Nemiro.OAuth a try? It's easy to set up, supports asp.net and winforms, and the online documentation is very detailed.
protected void RedirectToLogin_Click(object sender, EventArgs e)
{
// gets a provider name from the data-provider
string provider = ((LinkButton)sender).Attributes["data-provider"];
// build the return address
string returnUrl = new Uri(Request.Url, "ExternalLoginResult.aspx").AbsoluteUri;
// redirect user into external site for authorization
OAuthWeb.RedirectToAuthorization(provider, returnUrl);
}
protected void Page_Load(object sender, EventArgs e)
{
var result = OAuthWeb.VerifyAuthorization();
Response.Write(String.Format("Provider: {0}<br />", result.ProviderName));
if (result.IsSuccessfully)
{
// successfully
var user = result.UserInfo;
Response.Write(String.Format("User ID: {0}<br />", user.UserId));
Response.Write(String.Format("Name: {0}<br />", user.DisplayName));
Response.Write(String.Format("Email: {0}", user.Email));
}
else
{
// error
Response.Write(result.ErrorInfo.Message);
}
}
You can also follow this tutorial for a step-by-step instruction on how to use OAuth with Nemiro.OAuth library.

Publishing Post on Facebook C# Sdk ,Desktop Application

I am confused about publishing a post on facebook using C# sdk
I want to publish Name ,Description and photo on my page:
Do i need "publish_actions " in "items in review"(permissions)? because it is my own page .
When i try to add publish_actions ,facebook asks for privacy policy url ,How am i supposed to make it using C# Desktop Application, I didn't Found useful help on google.
Settings:
I have added http: //localhost:80/ to my site URL and:
http://abbasnaqvi512.tumblr.com/ to Valid OAuth redirect URIs.
Native or desktop app?=Yes
Is your App Secret embedded?=No
Client OAuth Login=yes
Embedded browser OAuth Login=NO
App Secret Proof for Server API calls=No
Require 2-factor reauthorization=No
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
try
{
if (e.Url.OriginalString.Contains("assets") && e.Url.OriginalString.Contains("code"))
{
code = Regex.Matches(e.Url.OriginalString, "assets.tumblr.com.*?code%3D(?<data>.*?)&")[0].Groups["data"].Value;
richTextBox1.Text += "\n\n" + code + "\n\n";
if (String.IsNullOrEmpty(code) == false)
{
webBrowser1.Stop();
webBrowser1.Dispose();
ShareOnFB();
}
}
}
catch (Exception)
{
}
}
private void ShareOnFB()
{
string pageId = "ABC";
FacebookClient client = new FacebookClient(code);
dynamic messagePost = new ExpandoObject();
messagePost.access_token = code;
messagePost.picture = "http://fc02.ostadreza-d6pkzrd.jpg";
// messagePost.link = "http://www.examplearticle.com";
messagePost.name = "NAME";
messagePost.description = "DESCRIPTION";
var result = client.Post(string.Format("/{0}/feed", pageId), messagePost);
richTextBox1.Text += "\n\n"+result+"\n\n";
}
Rightnow it is giving me Error
"Malformed access token AQA44CIJCyoV7_Xlz3mtvdPErPBrmtF6ykz6teCc9QINrfePHxEOiQKIyl8wgxH1mvQxEtLE-xnVfdyfiE38eA2M1YU7RS22MNIKNUh5wMmd2zwPCLj30PiEaq6CKIfcq9yIvq_slblOWmE4LYcynyH_pJuZcPc3EqLCQoCUBtSO58X1WtiohRoRvq70QWHpZec-7jhzUQnW75nlk4wpEwcJ9yOcBlPbne72sV6yX_hqndI5RKVDjqRJzdOscOblbLCkC1xtI0rMD1bCJufvpAa-tMsIyG6ATqrk6TNqXXASlcvialbzh0WttS2x-j_J59LF7cBh22T18P8qOly5cOwF"
Thanks for reading my question ,Kindly help me,
Update: I have added publish_actions in review by adding tumblr privacy policy url ,Notes and screen shots of my application ,It is on review

Facebook SDK for .NET Login Button, logout code

I've used the Login Button Control in the Facebook SDK for .NET in an app and I need to change the Status/state of the login button control from "Logout" to "Login" i.e., I need to logout the user manually through code.
How would that be possible??
Use FacebookClient.Logout to generate the logout url.
This is just a sample.
private void btnLogout_Click(object sender, EventArgs e)
{
var fb = new FacebookClient();
var logoutUrl = fb.GetLogoutUrl(new
{
next = "https://www.facebook.com/connect/login_success.html",
access_token = _accessToken
});
var webBrowser = new WebBrowser();
webBrowser.Navigated += (o, args) =>
{
if (args.Url.AbsoluteUri == "https://www.facebook.com/connect/login_success.html")
Close();
};
webBrowser.Navigate(logoutUrl.AbsoluteUri);
}
Make sure to persist the access token somewhere when you login so that you can use it to the logout too.
The user is not asked for his credentials because the Facebook authentication cookie is still present in the WebBrowser control.
So to completely logout the user from Facebook, you need to clear the WebBrowser cookies.
Unfortunately, there is no easy way for erasing cookies on Windows Phone 7.
On Windows Phone 8 you just need to call ClearCookiesAsync Method
await new WebBrowser().ClearCookiesAsync();
Here is a tutorial that makes use of it:
Integrate Facebook to Your Windows Phone Application
I've spent many hours trawling to get this. Many thanks Kulasangar
I modified your code slightly but it works:
var identity = AuthenticationManager.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie);
var accessToken = identity.FindFirstValue("FacebookAccessToken");
var fb = new FacebookClient(accessToken);
var logoutUrl = fb.GetLogoutUrl(new
{
next = "https://www.facebook.com/connect/login_success.html",
access_token = accessToken
});
Response.Redirect(logoutUrl.AbsoluteUri);

Log in as a different user doesnt work in facebook sdk for .net in windows phone

I am using facebook SDK for .NET to integrate facebook to windows phone application.
the facebook log in screen appears when I try to log in for the first time. Then if i sign out and sign in again the same user gets signed in.
My code is as follows:
for login
session = await App.FacebookSessionClient.LoginAsync("user_about_me,read_stream");
for logout
App.FacebookSessionClient.Logout();
How to log in as different user?
I think the implementation of FacebookSessionClient.Logout() is not complete for now. Here is the code can do the trick for you:
private void m_buttonLogout_Click(object sender, RoutedEventArgs e)
{
var fb = new FacebookClient();
var logoutUrl = fb.GetLogoutUrl(new {
next = "https://m.facebook.com/connect/login_success.html",
access_token = App.FacebookSessionClient.CurrentSession.AccessToken;
});
var webBrowser = new WebBrowser();
webBrowser.Navigated += (o, args) =>
{
if (args.Uri.AbsoluteUri == "https://m.facebook.com/connect/login_success.html")
{
App.FacebookSessionClient.Logout();
NavigationService.GoBack();
}
};
webBrowser.Navigate(logoutUrl);
}//private void m_buttonLogout_Click(object sender, RoutedEventArgs e)

Categories

Resources