How do I resolve the OAuthException 100 Requires user session error when accessing Facebook? - c#

I created my app and sent a request to Facebook with the following parameters:
facebookClient.AppId = APP_ID;
facebookClient.AppSecret = APP_SECRET;
facebookClient.AccessToken = APP_ACCESS_TOKEN;
However, when I try to get page statuses, I get the error:
OAuthException 100 Requires user session
What does this error mean? How do I resolve it?
Using a Facebook C# SDK to get this error.
The user that created this app has the manage_pages permission on the page I want to get status updates from.

To query for the "page statuses", you need to pass the user_access_token, not the app_access_token.
The user access token is obtained at the authorization step. For eg:
//authorization
session = await App.FacebookSessionClient.LoginAsync("manage_pages");
string access_token = session.AccessToken;
string fb_id = session.FacebookId;

Related

How do I convert from an app token to a page token using the Facebook graph API?

I'm using the Facebook .NET SDK.
I can generate an app access like so:
var client = new FacebookClient();
dynamic appAccessToken =
client.Get(
string.Format("/oauth/access_token?client_id={0}&client_secret={1}&grant_type=client_credentials", appId, appSecret));
which brings me back an access token in the format {appId}|{token}
If I then pass this back into the client object I hoped to get a page access token, but I'm just getting back the page Id, where I as expecting to get the page Id and an access token.
Full code:
var client = new FacebookClient();
dynamic appAccessToken =
client.Get(
string.Format("/oauth/access_token?client_id={0}&client_secret={1}&grant_type=client_credentials", appId, appSecret));
client.AccessToken = appAccessToken.access_token;
dynamic tokens = client.Get(string.Format("/v2.5/{0}?fields=access_token", pageId));
To get a Page Token, you need to authorized with the manage_pages permission and use the /me/accounts endpoint to get Page Tokens for all your Pages. Or /page-id?fields=access_token for a single Page. You MUST use a User Token with manage_pages though, you can´t just use an App Token. App Tokens are not tied to a User (and the Pages he manages).
More information:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
Make sure you understand the difference between App Token, User Token and Page Token. And of course you can´t get a Page Token for Pages you don´t manage, just in case it´s not clear.

C# ASP.NET Azure Mobile Services InvalidOperationException

try
{
JObject jO = new JObject();
// Change 'MobileService' to the name of your MobileServiceClient instance.
// Sign-in using Facebook authentication.
user = await client.LoginAsync(provider, jO);
Session["userId"] = user.UserId;
Session["authToken"] = user.MobileServiceAuthenticationToken;
}
catch (InvalidOperationException)
{
// error
}
I'm getting error saying I must specify the access token.
The POST Facebook login request must specify the access token in the body of the request.
Does it mean I need to add the Facebook SDK into my project and have to get the access token via the SDK and add it into the JObject?
Yes you need to use the Facebook SDK to get the access_token then add it to your JObject using the following:
jO.Add("access_token", JsonValue.CreateStringValue(accessToken));
I think this post has what you're looking for.
Authenticating with Facebook for Mobile Services in Azure

Session not getting retrieved in Facebook C# SDK example

I am a newbie at ASP.net programming. This is in reference to the Facebook C# SDK, I have managed to set up all the steps required for authentication on this SDK. However, I keep getting a null from the following code:
(reference: http://csharpsdk.org/docs/web/getting-started#5)
var accessToken = Session["AccessToken"].ToString(); //This line returns null and crashes
var client = new FacebookClient(accessToken);
dynamic result = client.Get("me", new { fields = "name,id" });
string name = result.name;
string id = result.id;
Just like in the example, I had set up a generic handler to set up the session variable to be stored in the HttpContext.Session object.
I even tried to modify the offending line to directly access the HttpContext and retrieve the access token:
var accessToken = HttpContext.Current.Session["AccessToken"].ToString();
but this yielded the same result.
Have I missed out something in the webconfig or is there some other way I can store the access token when shifting from the handler to the log in page?
Make sure in your Facebook developer settings that you do not have query string selected for your app as auth token paramenter!!!
This is the default mode and this wont work unless you do the following:
http://developer.facebook.com
Open your app page.
Then go Settings --> Auth Dialog --> Auth Token Parameter and select URI Fragment.
100% sure this is your problem. It's not included in any literature I found, and it's a damn shame.
If it is returning null then I would assume that the Session value is not being set - have you debugged to make sure the code which sets the session is being hit?
Looking at the linked article - it uses a HttpHandler to do this bit but does not mention anything about registering it in the Web.Config - have you done this? If not see here http://msdn.microsoft.com/en-us/library/46c5ddfy.aspx

facebook c# sdk: deleting a request-id

I am using the latest facebook c# sdk (http://facebooksdk.codeplex.com/). After i have sent an apprequest, i want to delete the request id.
This is how i do it at the moment:
var app = new FacebookClient(appid, appsecret);
app.Delete(requestID);
But i am not sure if its get deleted or not. If i try to see if it still exist using the graph api i get:
{
"error": {
"type": "GraphMethodException",
"message": "Unsupported get request."
}
}
But the user still has the request in his notification area. So my question is> Is the request deleted, or did i miss something? Thanks
var url = "https://graph.facebook.com/{0}?access_token={1}";
fb.Delete((String.Format(url, fullRequestId, fb.AccessToken)));
First parameter is requestId and user id like -> fullRequestId = requestId + "_" + fbUser.id
Second parameter is Accesstoken
I'm just getting started on this myself, but I'm guessing that you need to instantiate the FacebookClient with the authorization code from the user, not with your application data. The way I understand it, the request is sent by the user not your application. Hence the need to use the users authorization code to get information about the requeset.
This is what's working for me (sorry it's VB.Net):
Dim fb As FacebookClient = New FacebookClient(Config.FacebookAppId,Config.FacebookAppSecret)
Dim result = fb.Delete(String.Format("{0}_{1}?access_token={2}", facebookRequestId, facebookUserId, fb.AccessToken))

DotNetOpenAuth with Google Calendar Feed

I have been racking my brain for a few days trying to get a list of calendars from Google using DotNetOpenAuth.
I can successfully get a list of contacts using the DotNetOpenAuth Samples. I have integrated it with my domain using the OpenId+OAuth. Everything works great to get a list of contacts.
So from there I modified the code to try to retrieve a list of Calendars and I keep getting a 401 Unauthorized error.
I know it is authorizing because I can get the contact list. Does anyone have a code example how they are retrieving calendars or calendar events using the DotNetOpenAuth with Google???
Thanks
Update:
Thanks for the response. I have read everything I can get my hands on. Here is what I have done so far
Step 1: I created a new GetCalendarEndPoint in the GoogleConsumer.cs
private static readonly MessageReceivingEndpoint GetCalendarEndpoint = new MessageReceivingEndpoint("https://www.google.com/calendar/feeds/default", HttpDeliveryMethods.GetRequest);
Step 2: Next I created a new method GetCalendars patterned after the GetContacts Method in GoogleConsumer.cs - (Rebuilt the dll etc.)
public static XDocument GetCalendars(ConsumerBase consumer, string accessToken, int maxResults/* = 25*/, int startIndex/* = 1*/) {
if (consumer == null)
{
throw new ArgumentNullException("consumer");
}
var request = consumer.PrepareAuthorizedRequest(GetCalendarEndpoint, accessToken);
var response = consumer.Channel.WebRequestHandler.GetResponse(request);
string body = response.GetResponseReader().ReadToEnd();
XDocument result = XDocument.Parse(body);
return result;
Step 3: In my Application I modified the ScopeURI to the the Calendar URI from GoogleConsumer as follows
private IAuthenticationRequest GetGoogleRequest()
{
Realm realm = Request.Url.Scheme + Uri.SchemeDelimiter + Global.GoogleTokenManager.ConsumerKey + "/";
IAuthenticationRequest authReq = relyingParty.CreateRequest(GoogleOPIdentifier, realm);
// Prepare the OAuth extension
string scope = GoogleConsumer.GetScopeUri(GoogleConsumer.Applications.Calendar);
Global.GoogleWebConsumer.AttachAuthorizationRequest(authReq, scope);
// We also want the user's email address
var fetch = new FetchRequest();
fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
authReq.AddExtension(fetch);
return authReq;
}
However, when I run the app I get 401 Unauthorized when I make the following call
var calendars = GoogleConsumer.GetCalendars(Global.GoogleWebConsumer, State.GoogleAccessToken, 25, 1);
I have also checked that the State.GoogleAccess token exists by simply displaying it on my screen before I trigger the method that makes this call.
Again, if I exectute
var calendars = GoogleConsumer.GetContacs(Global.GoogleWebConsumer, State.GoogleAccessToken, 25, 1);
then it works??????? Thanks for you help.
I've been suffering through exactly the same thing for most of the weekend.
I think that after much fiddling with Fiddler I've found the cause and have a solution which, although not pretty, seems to work. I found that I was able to access the calendar feed by copying and pasting the DNOA-generated Uri into a browser, but always got a 401 when attempting programmatic access. This is apparently because the default auto-redirect behavior of HttpWebRequest discards any cookies that the redirect is attempting to set. The Contacts feed doesn't set any cookies during the redirect, so it is immune.
The first time you request a calendar feed (even with a properly constructed and signed OAuth request), Google replies with a redirect containing a cookie. If you don't present that "calendar cookie" at the same time as your feed request you will get a 401 Unauthorized when you attempt to follow the redirect to the feed.
here's the cookie-setting header from Google:
HTTP/1.1 302 Moved Temporarily
Set-Cookie: S=calendar=y7AlfgbmcqYl0ugrF-Zt9A;Expires=Tue, 10-Jan-2012 03:54:20 GMT;Secure
Here's what I'm doing to make it work:
// wc: WebConsumer
var calRequest = wc.PrepareAuthorizedRequest(erp2, authTokenRsp.AccessToken);
// need to stop redirect to capture calendar cookie token:
calRequest.AllowAutoRedirect = false;
var calResponse = calRequest.GetResponse();
var redirectCookie = calResponse.Headers[System.Net.HttpResponseHeader.SetCookie];
var cookiedCalRequest = wc.PrepareAuthorizedRequest(erp2, authTokenRsp.AccessToken);
cookiedCalRequest.Headers[System.Net.HttpRequestHeader.Cookie] = redirectCookie;
var calFeedResponse = cookiedCalRequest.GetResponse();
Have you read the Google Calendar data API documentation to make sure you have the right endpoints programmed in? Have you also modified the code that acquires the access token to request access to Google Calendar in addition to Google Contacts? The access token in the sample only gets Contacts permissions unless you change it.

Categories