Logging out from facebook using facebook c# sdk in WP7 - facebook

I want to implement logout from facebook using facebook C# sdk in my windows phone app
My primary question is how do we logout using Facebook C# SDK in WP7
I found this article in search
Article link
there he is trying to find the logout url using regex, but that did not working in my app
when i try that the browser navigated event is going into infinite loop
you can share any samples/posts related to facebook logout in windows phone 7.
I want logout should happen with out user intervention, after he clicks on a button he should looged out from facebook and from next time he should see the login page
I tried following posts/blogs also but no use.
LINK 1
LINK 2 this giving error while splitting the accesstoken
UPDATE
LogOutButtonCode
FacebookClient _fbClient = new FacebookClient(fbaccess.AccessToken);
var logoutParams = new Dictionary<string, object>();
logoutParams.Add("next", "https://www.facebook.com/connect/login_success.html");
//logoutParams.Add("",)
var logoutUrl = _fbClient.GetLogoutUrl(logoutParams);
BrowserControl.Navigated += new EventHandler<System.Windows.Navigation.NavigationEventArgs>(BrowserControl_Navigated);
BrowserControl.Navigate(new Uri(logoutUrl.AbsoluteUri));
Navigated Event CODE
if (e.Uri.AbsoluteUri == "https://www.facebook.com/connect/login_success.html")
{
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
e.Uri.AbsoluteUri returns https://www.facebook.com/home.php
Logout URL i am getting from the server https://www.facebook.com/logout.php?next=https://www.facebook.com/connect/login_success.html

Use FacebookClient.Logout to generate the logout url.
This is the snippet from winforms sample which will work in wp7 with some modifications.
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 as it is required to logout.

Related

Xamarin.Auth Facebook login Completed event not firing

I am trying to create a Xamarin.Forms application with a Facebook login button. Everything works up until the part where the Completed event, which never gets fired.
I am using a PageRenderer to initiate the auth flow as follows:
[assembly: ExportRenderer(typeof(Page1), typeof(LoginPageRenderer))]
namespace xmrn1.Droid {
class LoginPageRenderer : PageRenderer {
private const string ClientId = "<sanitized>";
public LoginPageRenderer(Context ctx) : base(ctx) { }
protected override void OnElementChanged(ElementChangedEventArgs<Page> e) {
base.OnElementChanged(e);
var authorizeUri = new Uri("https://www.facebook.com/dialog/oauth/");
var redirectUri = new Uri($"fb{ClientId}://authorize");
var auth = new OAuth2Authenticator(
ClientId,
"email",
authorizeUri,
redirectUri);
auth.Completed += Auth_Completed;
var ui = auth.GetUI(Context);
Context.StartActivity(ui);
}
private void Auth_Completed(object sender, AuthenticatorCompletedEventArgs e) {
// This never gets called
}
}
}
And this is my "Facebook Login" settings:
And my "Advanced Settings" settings:
Found the answer, I had to turn on the Web OAuth Login in the Facebook Login settings, and also to change the redirectUri to some uri in my domain, and add that uri to the Valid OAuth Redirect URIs in that same settings window.
Strange thing though, now when I log in, and the two-factor-authentication code prompt shows up, my phone displays an authenticator popup notification asking me to approve and when I press "Yes" it doesn't automatically confirm the login, I have to manually type the 2fa code anyway...

Facebook OAuth Xamarin Forms Redirection

I am using xamarin forms OAuth2 to signin into Facebook, Google and Twitter.
On android it works. But on iOS it screen freezes with spinning activity indicator at top right corner. Is there any one having same issue ?.
Update: Please find below code
partial void UIButton15_TouchUpInside(UIButton sender)
{
// https://developers.facebook.com/apps/
var auth = new OAuth2Authenticator(
clientId: "ID",
scope: "",
authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),
redirectUrl: new Uri("http://www.facebook.com/connect/login_success.html"));
var ui = auth.GetUI();
auth.Completed += FacebookAuth_Completed;
PresentViewController(ui, true, null);
}
async void FacebookAuth_Completed(object sender, AuthenticatorCompletedEventArgs e)
{
if (e.IsAuthenticated)
{
var request = new OAuth2Request(
"GET",
new Uri("https://graph.facebook.com/me?fields=name,picture,cover,birthday"),
null,
e.Account);
var fbResponse = await request.GetResponseAsync();
var fbUser = JsonValue.Parse(fbResponse.GetResponseText());
var name = fbUser["name"];
var id = fbUser["id"];
var picture = fbUser["picture"]["data"]["url"];
var cover = fbUser["cover"]["source"];
}
DismissViewController(true, null);
}
On facebook developer site:
Created app using Facebook login plugin.
Added redirect URL as http://www.facebook.com/connect/login_success.html
UPDATED :
Below code works
PresentViewController(auth.GetUI(), true, false);
It seems like issue happening only with latest OAuth library. Couldn't build with previous versions of OAuth due to build errors. So created Webview based login followed by Graph API Request.

how to share to facebook without showing feed dialog in android application?

I tried a lot about sharing to facebook without showing dialog using facebook android sdk,but could not get solution. Please help me to share to facebook without dialog.
Use GraphReqest. This code posts a Bitmap image on facebook with caption using facebook sdk 4.2
Bitmap bmp;
String caption;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
final JSONObject graphObject=new JSONObject();
Callback callback=new Callback() {
#Override
public void onCompleted(GraphResponse response) {
// your code
}
};
GraphRequest request=GraphRequest.newPostRequest(AccessToken.getCurrentAccessToken(), "me/photos", graphObject, callback);
Bundle params = new Bundle();
//params.putString("method", "photos.upload");
params.putString("caption", caption);
params.putByteArray("picture", byteArray);
request.setParameters(params);
request.executeAsync();
You will have to take publish_actions permissions from the user
LoginManager.getInstance().logInWithPublishPermissions(this, Arrays.asList("publish_actions"));
Moreover, If your app requires publish_actions, then you also need to send your app for the review on fb developers page, otherwise it will only work for developer accounts and tester accounts.

get user images twitter | angular.js | firebase

im quite new to angular.js and firebase, so im starting to edit some code from an open source script to expens my knowledge ... i used a chat script with a facebook login.
i decided to go change the facebook login to a twitter login. (firebase lets you use logins pretty easy)
function onLoginButtonClicked() {
auth.login("Twitter");
}
the code also automaticly gets the user image from facebook with
<div id="comments">
<script id="template" type="text/template">
<img class="pic" src="https://graph.facebook.com/{{userid}}/picture">
<span><b>{{name}}</b><br/>{{body}}</span>
</script>
But now i changed it to an twitter app i wonder how i can get the twitter user icons instead?
--edit--
whats wrong with the question?
If you check out the user info returned from the login process, you'll see that it contains a an object called thirdPartyUserData. It contains all of the information provided by twitter during login; this is their purview and could change when their API or policies change in the future, but has (for as long as I've been familiar with the Twitter API) contained URLs for user's avatars:
var ref = new Firebase(URL);
var auth = new FirebaseSimpleLogin(ref, function(err, user) {
if( err ) console.error(err);
console.log('avatar is ', user && user.thirdPartyData.profile_image_url);
});
$('button').click(function() {
console.log('clicked it');
auth.login('twitter');
});
(Side note: the login provider is twitter vs Twitter)
There is another way to get the Twitter avatar which works better since getting it from the login user object is only for the logged in user and so would require that the URLs be saved which would then be a problem if the user ever changed their twitter avatar since the URL would then be missing. After some searching around I found that the twitter avatar (or facebook) avatar can be reached from the firebase user id as follows:
var info = userId.split(':');
var provider = info[0];
var id = info[1];
if ( provider === 'facebook' ) {
return 'https://graph.facebook.com/' + id + '/picture?type=square';
} else if ( provider === 'twitter' ) {
return 'http://twitter.com/api/users/profile_image/' + id + '?size=normal';
}

Facebook action script 3 API login/logout issue

I'm making mobile AIR app for Android using Flash builder 4.5, AIR 2.6, Facebook action script 3 API the latest version.
I have a problem with login/logout. I can login only one time - then my data caches somehow and Facebook automatically logs me in. When I call logout I receive response TRUE, but I don't really logout from system. Standard login dialog doesn't appear for me. I have already read a lot of articles on stackoverflow and open issues on official site, but none of them were helpfull. How can I solve this? Here is the code I use:
package
{
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.external.ExternalInterface;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.system.Capabilities;
import flash.system.Security;
import flash.display.Loader;
import com.facebook.graph.FacebookMobile;
public class TestProj extends Sprite
{
public function TestProj()
{
super();
//register to add to stage
this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
// support autoOrients
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
}
private function onAddedToStage(event:Event):void
{
this.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
FacebookMobile.init("195053007196177", initCallback);
}
private function initCallback(success:Object, fail:Object):void
{
var appPermissions:Array = new Array("read_stream", "offline_access", "publish_stream", "read_friendlists");
FacebookMobile.login(loginCallback, this.stage, appPermissions);
//FacebookMobile.logout(logoutCallback);
}
private function loginCallback(success:Object, fail:Object):void
{
//And here I always receive success with my UserID
//and login dialog don't appears to me before this
if (success)
{
trace("login ok");
}
else
trace("login failed");
}
private function logoutCallback(success:Object):void
{
//here I reseive "TRUE" always!!
trace(success);
}
}
}
You're only passing the 1st argument of logoutCallback to your logout method. If you add in the 2nd argument of your site url specified for your app, it should clear it out the html cookie for that window. Also, set FacebookMobile.manageSession = false;
FacebookMobile.logout(logoutCallback, "http://your_app_origin_url");
There is a potential, related bug that involves Desktop and Mobile not accessing or clearing the access token's the same way. For that, there's a hack that describes exposing the access token in FacebookMobile, then manually calling the "logout" method with the access token. The issue is described here, including a method called "reallyLogout". If what I've written above doesn't work, implement "reallyLogout".
When you log out, your app clears the local session but does not log you out of the system. This is clearly defined in the documentation for logout. Think about it, if you're logged into Facebook on your Smartphone, Web Browser, and now this Mobile Desktop App, and suddenly you log out... it shouldn't log you out EVERYWHERE, just within that browsers session. So pass that 2nd parameter.
I've had this exact problem, and after trying numerous fixes, this finally seems to work:
The default logout functionality seems to not be properly clearing cookies via the FacebookMobile actionscript API. The solution in comment #33 here worked for me, reproduced here. Make sure to sub in your own APP_ID:
function logout(e:MouseEvent):void {
FacebookMobile.logout(onLogout, "https://m.facebook.com/dialog/permissions.request?app_id=APP_ID&display=touch&next=http%3A%2F%2Fwww.facebook.com%2Fconnect%2Flogin_success.html&type=user_agent&perms=publish_stream&fbconnect=1");
}
function onLogout(result:Object):void
{
trace("Perfect Log Out!")
}
Have had this Android Facebook clean logout problem the whole day, manage to solve it. Hope it helps. Here is my FB mobile handlelogin code to ensure all fb cookies and sessions are being removed and user will need to relogin.
Sometimes FB server is very slow. Its best to put a timer before you call handleLoginClick() again
function handleLoginClick():void
{
trace("connecting to facebook");
if (FacebookMobile.getSession() == null)
{
FacebookMobile.init(APP_ID, onHandleInit, null);
FacebookMobile.manageSession = false
}
else
{
var webView:StageWebView = new StageWebView();
webView.viewPort = new Rectangle(0, 0, 1, 1);
webView.stage = this.stage;
webView.loadURL("https://m.facebook.com/logout.php?confirm=1&next=http://www.facebook.com&access_token=" + FacebookMobile.getSession().accessToken);
webView.addEventListener(Event.COMPLETE,webviewhandleLoad);
function webviewhandleLoad(e:Event)
{
FacebookMobile.logout(null, "http://apps.facebook.com/<appName>/");
FacebookMobile.logout(null, "http://www.facebook.com");
webView.dispose()
webView = null
setTimeout(handleLoginClick,3000)
}
}
}
look at the solution of this problem. Maby someone it helps:
var stage_ref:Stage = PlatformUtil.originalStage(); //my custom class to get stage
var webView:StageWebView = new StageWebView();
webView.viewPort = new Rectangle(0, 0, stage_ref.width, stage_ref.height);
FacebookMobile.login(loginCallback, stage_ref, appPermissions, webView);
http://code.google.com/p/facebook-actionscript-api/issues/detail?id=381
http://code.google.com/p/facebook-actionscript-api/issues/detail?id=382
http://code.google.com/p/facebook-actionscript-api/issues/detail?id=383