Posting to a Facebook page without logging in using C# - c#

I've read a lot of posts about how to handle posting to FB without logging in - specifically in my instance to a managed page, some using the defunct "offline_access" method, others relating to tokens.
I've created a token from my graph API - https://developers.facebook.com/tools/explorer
I've also created a little test in some code e.g.
FacebookClient fb = new FacebookClient("Access_Token"]);
Dictionary<string, object> argList = new Dictionary<string, object>();
argList["message"] = "my message";
fb.Post("mypage/feed", argList);
This works perfectly as expected and posts to the page wall in question. If however I log out of Facebook, it doesn't work and in turn throws an error.
Facebook.FacebookOAuthException: (OAuthException - #190)
Error validating access token: This may be because the user logged out
I'm stuck about why this happens when I've set the permissions correctly in the https://developers.facebook.com/tools/explorer area e.g. "publish_stream", "manage_pages" etc.
I've even assigned the token to an app I've created too which still doesn't help.
Has anyone got an example in C# that illustrates how to post when you are not logged in?
Thanks in advance,
Deeds.

Its may be because of access token validation expired, if you have application Id and Secret key of which you used to generate access token, You can use the following code to extend the access token validation period upto 60 days .
public string exchange_access_token(string actoken)
{
var fb = new FacebookClient();
dynamic result = fb.Get("oauth/access_token", new
{
client_id = "xxxxxxxxx",
client_secret = "xxxxxxxxxxxx",
grant_type = "fb_exchange_token",
fb_exchange_token = actoken
});
return result;
}
But if you dont have application details you cant do this ...

Related

Email Audit API - 403 Forbidden

I am trying to download a user's mailbox using the Email Audit API. I am getting a 403 Forbidden response to this code (the error occurs on the last line, the call to the UploadPublicKey method):
var certificate = new X509Certificate2(System.Web.HttpRuntime.AppDomainAppPath + "key.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { "https://apps-apis.google.com/a/feeds/compliance/audit/" }
}.FromCertificate(certificate));
credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Wait();
DebugLabel.Text = credential.Token.AccessToken;
var requestFactory = new GDataRequestFactory("My App User Agent");
requestFactory.CustomHeaders.Add(string.Format("Authorization: Bearer {0}", credential.Token.AccessToken));
AuditService aserv = new AuditService(strOurDomain, "GoogleMailAudit");
aserv.RequestFactory = requestFactory;
aserv.UploadPublicKey(strPublicKey);
I have created the service account in the Developers Console and granted the Client ID access to https://apps-apis.google.com/a/feeds/compliance/audit/ in the Admin console.
Seems to me like the account should have all the permissions it needs, yet it doesn't. Any idea what I am missing?
OK, so I gave up on trying to make it work with a service account even though that is what Google's documentation would lead you to believe is the correct way to do it. After emailing Google support, I learned I could just use OAuth2 for the super user account that created the application on the developer's console.
So then I worked on getting an access token for offline access (a refresh token) by following the process outlined here:
Youtube API single-user scenario with OAuth (uploading videos)
and then taking that refresh token and using it with this code:
public static GOAuth2RequestFactory RefreshAuthenticate(){
OAuth2Parameters parameters = new OAuth2Parameters(){
RefreshToken = "<YourRefreshToken>",
AccessToken = "<AnyOfYourPreviousAccessTokens>",
ClientId = "<YourClientID>",
ClientSecret = "<YourClientSecret>",
Scope = "https://apps-apis.google.com/a/feeds/compliance/audit/",
AccessType = "offline",
TokenType = "refresh"
};
OAuthUtil.RefreshAccessToken(parameters);
return new GOAuth2RequestFactory(null, "<YourApplicationName>", parameters);
}
which is code from here https://stackoverflow.com/a/23528629/5215904 (Except I changed the second to last line... for whatever reason the code shared did not work until I made that change).
So there I was finally able to get myself an access token that would allow me access to the Email Audit API. From there everything was a breeze once I stopped trying to mess around with a service account.

Getting facebook access token in c#

var fb = new FacebookClient();
dynamic result = fb.Get("oauth/access_token", new
{
client_id = "MyAppId",
client_secret = "MyAppSecret",
redirect_uri = "http://www.facebook.com/connect/login_success.html",
code = "code"
});
fb.AccessToken = result.access_token;
I use this piece of code to get facebook access token. When I try to login with any account, there is no problem. However, if I try to post something on that account's wall, I get an error which is;
(OAuthException-#200)(#200) The user hasn't authorized the application
to perform this action.
Also I want to add that if I get the access token from graph api explorer in developers.facebook.com manually and use it in my code as access token, I can post.
P.S: I gave "publish_actions" permission to the account and nothing is changed.
Can you verify that your have requested permissions using /{user-id}/permissions ?
See https://developers.facebook.com/docs/facebook-login/permissions/v2.4 for details.

Using Facebook API to access public group event data

I'm developing a public website and what I want to do is pretty straightforward, but I'm pulling my hair out trying to get everything working right.
I administer an open Facebook group and I want to display the public facebook events of this group on my website.
I can't seem to figure out how to setup my authentication so that I can access the event data. Here is my code for using my application to get an auth token:
var fb = new FacebookClientWrapper();
dynamic result = fb.Get("oauth/access_token", new
{
client_id = AppSettings.AppID,
client_secret = AppSettings.AppSecret,
grant_type = "client_credentials"
});
fb.AccessToken = result.access_token;
I know this works fine because I can access some information - for example, if I access a specific event by its ID, I can retrieve that information.
The problem occurs when I try to retrieve a list of events with fields within a date range:
[HttpGet]
public object GetEventDetails(string unixStartDateTime, string unixEndDateTime)
{
var parms = new Dictionary<string, object>();
parms.Add("fields", new[] { "id","name","description","start_time","venue" });
if (!String.IsNullOrEmpty(unixStartDateTime)) { parms.Add("since", unixStartDateTime); }
if (!String.IsNullOrEmpty(unixEndDateTime)) { parms.Add("until", unixEndDateTime); }
var eventsLink = String.Format(#"/{0}/events", AppSettings.GroupID);
return ObjectFactory.GetInstance<IFacebookClient>().Get(eventsLink,parms);
}
(I'm aware that even if this did succeed, the return value wouldn't be serializable - I'm not concerned about that quite yet).
This GET request returns the following message:
(OAuthException - #102) A user access token is required to request this resource.
So the message is quite clear: I need a user access token to get the data I've requested. The question is - what is the best way to do this? Can I give my application a certain permission to read this data? I've looked over all the permissions available to apps, but I don't see one that would do the trick.
I don't want to require people to log onto Facebook to look at public event data, and I love the idea of allowing people with no technical experience to essentially update the website content by posting Facebook events to the group. Right now, I have to duplicate anything they do.
I would think this kind of application would be very common, but no matter what I've read or tried, I can't quite find an example of the same thing that works.
From the docs at https://developers.facebook.com/docs/graph-api/reference/v2.0/group/events you need
A user access token for a member of the group with user_groups permission.
To avoid the hassle, you could create such an Access Token via the Graph Explorer and then store it in your application. Remember to exchange that Access Token to a long-lived one (https://developers.facebook.com/docs/facebook-login/access-tokens/#extending), and that you have to renew the Access Token every 60 days afterwards.

Facebook SDK for .NET: Uploading pics to a page from backend

What I am looking to achieve.
I have a WPF application where in, I will be getting access to some pics generated on run time and I wanna post these pics to an album on FB Page(Think server to server interaction ). This process is supposed to be completely self reliant without any input from users. So I did some research and figured you gotta create an app to be able to do it. On further research the process seems to be as follows:
1) Using app secret and app id , get the app access token
2) Get the user access token
3) using this user access token, call {userId}/accounts and from the resulting JSON parse the page id and get the Page Access token.
Now I have successfully retrieved the App Access token and now I am not able to figure out how to get UserAccessToken without which I cant proceed to step 3.
I am using C# SDK for facebook and here is some code
Step 1.
var fbAccess = new FacebookClient();
dynamic resultAccess = fbAccess.Get("oauth/access_token", new
{
client_id = "XXXXXXXXX",
client_secret = "XXXXXXXXXXX",
grant_type = "client_credentials",
redirect_uri = "",
perms = "manage_pages, photo_upload, publish_stream"
});
String app_access_token = resultAccess["access_token"];
Step 2:
FacebookClient fbClient = new FacebookClient(app_access_token );
dynamic resultAccess = fbClient.Get("/{UserID}/accounts", new
{
client_id = "XXXXXXX",
client_secret = "XXXXXXXXXXXXXXXXX",
perms = "manage_pages, photo_upload, publish_stream"
});
The error I am getting is "A user access token is required to request this resource." I have already given the required permission to the app using Graph API Explorer.
Thanks in Advance

c# - how to get user access token without login from facebook?

I want to get user access token(Graph API Explorer) from facebook without login
I tried with app access token but I am unable to get comments for the posts
Code is for app access token:
string appId = "APP_Id";
string appSecret = "APP_Secret";
var fb = new FacebookClient();
dynamic result = fb.Get("oauth/access_token", new
{
client_id = appId,
client_secret = appSecret,
grant_type = "client_credentials"
});
fb.AccessToken = result.access_token;
var accessToken = fb.AccessToken;
Any ideas? Thanks in advance.
You have to create a new instance of the FacebookClient with the Users AccessToken to get info about the User!
I think here is no way you get the Token without calling the FB.Login
From the API Documentation:
User Access Token – The user token is the most commonly used type of token. This kind of access token is needed any time the app calls
an API to read, modify or write a specific person's Facebook data on
their behalf. User access tokens are generally obtained via a login
dialog and require a person to permit your app to obtain one.

Categories

Resources