Facebook multi account - c#

I want to write a simple win-forms tool for managing different social accounts.I have a problem if user has several Facebook accounts. When I try to log in as second user I just got redirecting page in webBrowser.I tried to use InternetSetOption and the INTERNET_SUPPRESS_COOKIE_PERSIST flag but it seems it does not help. How can I resolve this problem?
Login code
var lParameters = new Dictionary<string, object>();
lParameters["client_id"] = AppId;
lParameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
lParameters["response_type"] = "token";
lParameters["display"] = "popup";
lParameters["scope"] = "user_about_me";
Uri lUri = mFacebookClient.GetLoginUrl(lParameters);
Main.webBrowser.Navigate(lUri);
ADDED:
Maybe I'm doing something wrong with InternetSetOption? Sorry for newbie question. I really should use it like in this answer How do I use InternetSetOption? It looks difficult...

Most probable cause is because Facebook is setting a cookie with the session ID. INTERNET_SUPPRESS_COOKIE_PERSIST only makes cookies non-persistent, they will be cleared after the browser is destroyed or browser session finished, so if you are using the same instance they will still be alive.
You can finish your browsing session with InternetSetOption(0, 42, NULL, 0); (taken from here: http://social.msdn.microsoft.com/Forums/eu/csharpgeneral/thread/76a38eee-3ef6-4993-a54d-3fecc4eb6cff), so combining INTERNET_SUPPRESS_COOKIE_PERSIST and INTERNET_OPTION_END_BROWSER_SESSION (is what the 42 means) it should be cleared and ready for a new login.

Related

Clear all cookies from WebView

I am currently developing an application for Windows Phone 10 using UWP, in which I need a WebView that will set up several cookies in the process. The WebView can be instantiated many times, and I have noticed that the cookies do not get cleared on multiple instantiations, which makes it a bit difficult for my workflow (say, for instance, a user has to log in using the WebView, then when re-instantiating, the old state will be there).
I have tried using the clearTemporaryWebDataAsync to now avail. What is worse is that I don't know in advance the domains associated to the cookies, so I cannot do something like this:
HttpBaseProtocolFilter myFilter = new HttpBaseProtocolFilter();
HttpCookieManager cookieManager = myFilter.CookieManager;
HttpCookieCollection myCookieJar = cookieManager.GetCookies(new Uri("https://url.com"));
foreach (HttpCookie cookie in myCookieJar)
{
cookieManager.DeleteCookie(cookie);
}
Is there anything in the API that might help me wipe out all the cookies for the WebView, or at least get a list of them so that then I can use DeleteCookie on each?
What is worse is that I don't know in advance the domains associated to the cookies, so I cannot do something like this:
AFAIK, there isn't a method for clearing cache data except ClearTemporaryWebDataAsync, but the code snippet you provided does clear cookies. For what you consider about don't know in advance the domains to the cookies, you may get the current navigating Uri by the WebViewNavigationStartingEventArgs of NavigationStarting event handle. For example,
private void WebViewControl2_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
{
Uri gotouri = args.Uri;
HttpBaseProtocolFilter myFilter = new HttpBaseProtocolFilter();
HttpCookieManager cookieManager = myFilter.CookieManager;
HttpCookieCollection myCookieJar = cookieManager.GetCookies(gotouri);
foreach (HttpCookie cookie in myCookieJar)
{
cookieManager.DeleteCookie(cookie);
}
}
And this will clear the cookies of current Uri. But this will clear the cookies every time the WebView navigates. You may need to set a flag to ensure if the WebView is a new instance depending on your app logic.
Another thing, in apps compiled for Windows 10, WebView uses the Microsoft Edge rendering engine to display HTML content. Clear cookies of current WebView instance may also clear others, which is same as you found cookies still exists when you have a new instance.

Implementing refresh tokens in Xamarin (Authorization code flow - OAuth2)

Can anyone maybe share some tutorial, resources, link, anything related to implementing refresh tokens when using Xamarin.
What I am trying to accomplish is authentication code flow(where user firstly provides credentials to identity server, gets temporary code, which later gets exchanged for real access token, for accessing APIs).
I was looking all around, but nothing helped me. I have realized that implementing refresh tokens is not so easy in Xamarin, but still there must be a way.
I was trying something with TokenClient() class.
var client = new TokenClient("https://localhost:44305/connect/token", "mylegislature");
var request = await client.RequestResourceOwnerPasswordAsync(username, password);
if (!request.IsError)
{
_secureService.StoreAuthToken(request);
}
And with AuthorizeRequest() class:
var authorizeRequest =
new AuthorizeRequest("https://localhost:44305/connect/token");
var parameters = new Dictionary<string, string>();
parameters.Add("response_type", "token");
parameters.Add("client_id", "mylegislature");
parameters.Add("scope", "MyLegislatureAPI");
parameters.Add("redirect_uri", "https://localhost:44301/account/oAuth2");
var authorizeUri = authorizeRequest.Create(parameters);
But with non of them I have succeed in sending request to IdentityServer, which is ok since it is expecting respecting of authorization code flow of OAuth2, but I am unable to implement code in right way since I couldn't find any useful resources about this. If someone has something for sharing please help.

Facebook's OAuth "Given URL is not permitted by the Application configuration"

I was working on this program that connects my users through their Facebook accounts. It's been working quiet stable for the past couple of weeks, and I was able to add more value to my program during that period. However, starting today I was unable to connect through Facebook as I usually do. Whenever I ask for App authorization (1st step) I get a "Given URL is not permitted by the Application configuration" error, Even tho i didn't change anything in my App Settings.
I looked everywhere to check if maybe Facebook did some Updates or something, but couldn't find anything. Last time i logged in successfully was the 30th of March.
How could have this happened if I didn't edit any of my code, and apparently Facebook didn't either! Any help would be greatly appreciated :)
private string GenerateLoginUrlFacebook()
{
dynamic parameters = new ExpandoObject();
parameters.client_id = Globals.FBapplicationID;
parameters.redirect_uri = "https://www.facebook.com/connect/login_success.html";
parameters.response_type = "token";
parameters.display = "popup";
if (!string.IsNullOrWhiteSpace(Globals.FBextendedPermissionsNeeded))
parameters.scope = Globals.FBextendedPermissionsNeeded;
var fb = new FacebookClient();
Uri loginUri = fb.GetLoginUrl(parameters);
return loginUri.AbsoluteUri;
}

tweetsharp - app stops being able to tweet after a few hours

I have a asp.net 4.5 webforms site that allows users to link their account to twitter and tweet directly from my site.
My app is registered with twitter and I am able to successfully authorise my app for the user's account and initially can tweet fine, but after a few hours the tweets stop working. I am using tweetsharp to handle the authorisation.
my code is:
TwitterClientInfo twitterClientInfo = new TwitterClientInfo();
twitterClientInfo.ConsumerKey = ConsumerKey;
twitterClientInfo.ConsumerSecret = ConsumerSecret;
var requestToken = new OAuthRequestToken { Token = oauthtoken };
TwitterService twitterService = new TwitterService(ConsumerKey, ConsumerSecret);
OAuthAccessToken accessToken = twitterService.GetAccessToken(requestToken, oauthverifier);
twitterService.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
TwitterUser user = twitterService.VerifyCredentials(new VerifyCredentialsOptions());
SendTweetOptions options = new SendTweetOptions();
options.Status = tweetText;
twitterService.SendTweet(options);
what i have noticed is that while the app is successfully tweeting, the accessToken.Token value that is being used to authenticate the user has a proper value (a long string of numbers and upper/lowercase characters) however when it stops tweeting the accessToken.Token value is just a single question mark "?".
Twitter says it doesn't expire tokens so i am at a loss to understand what is happening or how it can be resolved? if i went in to my twitter account and deauthorised my app and went through the authorisation again it would work fine for a few hours, but obviously that's not something i can ask my users to do.
can anyone suggest a resolution to this - either to stop the accessToken value becoming ? or to handle it and get a proper value if it does (without reauthorising the app)
Well, without beginning to understand the actual issue, I managed to fix it
Instead of retrieving the access token every time via:
var requestToken = new OAuthRequestToken { Token = oauthtoken };
OAuthAccessToken accessToken = twitterService.GetAccessToken(requestToken, oauthverifier);
twitterService.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
i only do that once and store accessToken.Token and accessToken.TokenSecret in the database and retrieve them when tweeting and supply them
twitterService.AuthenticateWith(accessTokenFromDB, accessokenSecretFromDB);
I have seen somewhere that Twitter doesn't expire tokens, so this should work. Certainly it's been working for me all weekend whereas the original code would stop working after a few hours.
Thought this might help some others who have the same issue.

Facebook C# SDK - Post to wall

I'm developing an asp.net MVC 3 Facebook app and I am trying to post a message to my wall. Here is my code:
FacebookWebClient client = new FacebookWebClient();
// Post to user's wall
var postparameters = new Dictionary<string, object>();
postparameters["message"] = "Hello world!";
postparameters["name"] = "This is a name";
postparameters["link"] = "http://thisisalink.com;
postparameters["description"] = "This is a description";
var result = client.Post("/me/feed", postparameters);
I can get the access token using client.AccessToken, so I'm assuming I don't have to set it anywhere. This code produces no errors and for the result I get an ID. However, when I bring up my Facebook, I see nothing on my wall nor in my news feed. I'm not sure what I'm missing. I've looked at related questions here at StackOverflow, but I see no reports/questions similar to mine. I've also tried changing the code based on what I've seen in other posts, but to no avail. I also checked my Facebook account settings and I see my application listed with permission to post to my wall. I also tried posting a message to my wall via the Graph API explorer and I'm getting the same result. I get an ID in return, but when I check my Facebook account I see nothing. At been at this for a couple of days. Any help would be greatly appreciated.
Thanks in advance.
[EDIT]
I wonder if something is wrong with my app generated access_token. Using this access_token, as I mentioned in my post, I get the same result using the Graph API explorer. An ID is returned, but no message on my wall. However, if I give the Graph API explorer permission to post to my wall and use its own generated access_token, I can successfully post a message using the explorer. Here's the FB login button code:
<div>
<h1>Login using Facebook</h1>
<p><fb:login-button perms="user_location, publish_stream, email"></fb:login-button></p>
</div>
Basically you need to add an additional parameter into your post parameters.
args["access_token"] = account.access_token;
this is the token of the specific page.
I wont repeat the code, follow here for example: Post On Facebook Page As Page Not As Admin User Using Facebook C# SDK
(second answer)
Did you request right App permissions to Facebook in your action method?
Try: [CanvasAuthorize(Permissions = "user_location, publish_stream, email")]
Did you append the access_token to the URL? See example here. It's also documented here (see Using the Access Token).
/me/feed?access_token=<access_token>
with one small change, your code works fine for me. you have to pass the users auth token into the constructor like this...
var client = new FacebookClient(accessToken);
// Post to user's wall
var postparameters = new Dictionary<string, object>();
postparameters["message"] = "Hello world!";
postparameters["name"] = "This is a name";
postparameters["link"] = "http://thisisalink.com;
postparameters["description"] = "This is a description";
var result = client.Post("/me/feed", postparameters);
this method works for me, although i am not sure which facebook sdk you are using.
i'm using http://facebooksdk.net/ its quite good so if you're not using it i would recommend it

Categories