Getting access token for google+ with requested permissions - c#

I have been using google+ APIs for C# in my desktop application.I have to access the friends list of the google+ user.
I have been obtaining access token by extracting it from browser title.
It works fine for the following permissions(all grouped and asked at same time) and returns the authentication code in browser title(success=authcode).
"https://www.googleapis.com/auth/plus.me
"https://www.googleapis.com/auth/youtube",
"https://www.googleapis.com/auth/youtube.upload"
But when i changed the permission to obtain the friends list,
"https://www.googleapis.com/auth/plus.login
it's not returning the desired auth code ,it just returns success authuser=0&promt...
By the way I can't listen on local web server.
How to obtain the access token by using the above permission?

I just checked this and the success string in the window title is in fact different when you are using the plus.login scope. The code that is returned in the string is still valid though. The following code shows one way you could extract the authorization code from the window title string:
string pollActiveWindowForAuthCode(int sleepTime){
string activeTitle = GetActiveWindowTitle();
while (!activeTitle.StartsWith("Success"))
{
activeTitle = GetActiveWindowTitle();
Thread.Sleep(sleepTime);
}
// strip to start of auth code
string trimToAuthCode = activeTitle.Substring(activeTitle.LastIndexOf("=") + 1);
// trim the " - Google Chrome" text
return trimToAuthCode.Substring(0, trimToAuthCode.IndexOf(' '));
}
I have uploaded a more comprehensive demo to my GitHub:
csharp-gplus-wpf

Related

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 API get public profile wall posts

I'm making a small widget in c# to get the posts from a public facebook page/profile.
I believe you have to get a access token each time you make a request to the api?
I'm confused as to which access token I need and what url request string to use.
This is what I'm using currently but it brings back an unexpected looking key.
access_token=112121212121212|NxG_8djeufhfywhduEjaeU4J-lh4
(I've typed in random characters as an example of the structure).
string response = "https://graph.facebook.com/oauth/access_token?client_id=" + facebook_AppID + "&client_secret=" + facebook_AppSecret + "&grant_type=client_credentials";
string accesstoken = RequestResponse(response);
Then when I use that code to get the posts from a wall, using:
string urlGetFeed = "https://graph.facebook.com/thepagename?fields=access_token=" + accesstoken2 + ",posts.fields(message,picture)";
I get a ERROR : The remote server returned an error: (400) Bad Request. Error.
For the feed of a Facebook Page, you only need an App Access Token, which is easy to get:
APP-ID|APP-SECRET
For example:
string urlGetFeed = "https://graph.facebook.com/thepagename/feed?access_token=" + [app-id] + "|" + [app-secret];
Also, the Access Token is not a value of "fields", it´s a separate parameter.
The URL you should use is this:
https://graph.facebook.com/[THE_FACEBOOK_ID]/[WHAT_YOU_WANT]?access_token=[YOUR_ACCESS_TOKEN]&limit=[THE_LIMIT]
The first part access the Facebook graph.
The second part is the Facebook Id that you want.
The third part is the thing that you want from the Facebook Id that you entered (posts, feed, activities, etc). Here you must be sure that the Access Token has the permissions for what you want to get.
The fourth part is the Access Token that you get and the limit (if you don't set the limit the default limit from Facebook will be used).
Beware of the access token that you-re getting with the first line of code that you posted. That line will give you a short live access token. You should interchange the short live access token here:
https://graph.facebook.com/oauth/access_token?client_id=[YUOR_CLIENT_ID]&client_secret=[YOURCLIENT_SECRET]&grant_type=fb_exchange_token&fb_exchange_token=[THE_SHORT_LIVE_ACCESS_TOKEN]
EDIT:
What you should do is to include the FB Connect script:
<script type='text/javascript' src='http://connect.facebook.net/en_US/all.js#xfbml=1'</script>
and then use this function to take the user to the FB login (if it's not logged in) and then to the authorize page:
function createAccessToken()
{
FB.init({appId: '[YOUR APP ID]', status: true, cookie: true});
FB.login(function(response)
{
if (response.status == 'connected')
{
if (response.authResponse.accessToken)
{
var token = response.authResponse.accessToken;
}
else
{
alert('You must grant the permissions for this plugin or will not work.');
}
}
else
{
alert('You must be logged in to Facebook to grant permissions.');
}
}, { scope: 'read_stream' }); }
The token variable inside that function will contain the short lived access token to exchange for the long lived one here:
https://graph.facebook.com/oauth/access_token?client_id=[YOUR_CLIENT_ID]&client_secret=[YOURCLIENT_SECRET]&grant_type=fb_exchange_token&fb_exchange_token=[token]
Once you get that token go here to get what you want:
https://graph.facebook.com/[THE_FACEBOOK_ID]/[WHAT_YOU_WANT]?access_token=[YOUR_ACCESS_TOKEN]&limit=[THE_LIMIT]

C# Facebook SDK - How to use web forms to server side authorize canvas application

There are lots of sample applications in MVC but the current project I'm working on requires that I use web forms.
I can authorize the application using the javascript method but I want to use server side. Below is what I started with on the page.load
dynamic parameters = new ExpandoObject();
parameters.client_id = AppId;
parameters.client_secret = appSecret;
parameters.response_type = "code";
//parameters.state = state;
parameters.redirect_uri = "http://fb.local/page.aspx";
// The requested response: an access token (token), an authorization code (code), or both (code token).
parameters.response_type = "token";
// list of additional display modes can be found at http://developers.facebook.com/docs/reference/dialogs/#display
//parameters.display = "popup";
// add the 'scope' parameter only if we have extendedPermissions.
if (!string.IsNullOrWhiteSpace(ExtendedPermissions))
parameters.scope = ExtendedPermissions;
// generate the login url
var fb = new FacebookClient();
var loginUrl = fb.GetLoginUrl(parameters);
Response.Redirect(loginUrl.AbsoluteUri, true);
I can authorize but I'm not able to get the access token from the URL.
On the next page I can view source and see the access token in the url bar but I'm not sure how to go about getting it into the code. once I have the token, I'm all set.
page.aspx#access_token=AAACrxQhmdpY
I used to this code on my page load and works, its not a very clean code, but you may figure out how to change it for your best use. so the algorithm is that when the page loads you redirect the user to Facebook authentication page using response.redirect to a string that contains three parameters:your app ID(appid), what permissions you are asking your user(scope), where you want Facebook to redirect the user after authorization, and a parameter as state which i guess it should be a random number. so after the user authorized your application he/she will be redirected to your page, with a request URL that contains the same state you prepared Facebook with(and you can use to identify who which request was which if there are many requests i guess) and also a new "code" parameter which you pass on to Facebook to obtain access token, you can use Facebook c# sdk to obtain the access token.in my code there is a line that says "if code is not null, go to alireza" and alireza is a line tag after the response.redirect code, this is because you dont want the process to be repeated all over and over (and of course probably the browser show an error).
int intstate;
string strstate;
string redirecturltofb;
string scope;
string appid;
code = Request.QueryString["code"];
if (!String.IsNullOrWhiteSpace(code))
{
goto alireza;
}
appid = "424047057656831";
scope = "user_about_me,user_activities,user_groups,email,publish_stream,user_birthday";
intstate = 45;
strstate = Convert.ToString(intstate);
redirecturltofb = "https://www.facebook.com/dialog/oauth?client_id=" + appid + "&redirect_uri=http://test5-2.apphb.com/&scope=" + scope + "&state=" + strstate;
Response.Redirect(redirecturltofb);
You have to use Javascript SDK to get access token back to code behind.
Use FB.Init as in http://csharpsdk.org/docs/web/getting-started
and do post back on certain conditions to get the access token.
Thank you,
Dharmendra

Facebook access token only valid for user that created the facebook application

I have some JavaScript that logs in a Facebook user and saves the access token to a database:
window.fbAsyncInit = function () {
FB.init({
appId: '<%=FaceBookApplicationId() %>',
status: false, // check login status
cookie: true,
oauth: true
});
};
function facebookLogin() {
FB.login(function(response) {
if (response.authResponse) {
__doPostBack('__Page', 'FacebookDeliveryButton: ' + JSON.stringify(response.authResponse));
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, { scope: 'offline_access,read_stream,publish_stream,user_photos' });
}
A button click fires facebookLogin() which logs in a facebook user, getting a facebook session that includes an access token, which I JSON serialize and post to the server. The server then saves this access token to the database table FacebookDeliveryQueue.
I have a Windows service running that periodically queries the FacebookDeliveryQueue table and attempts to post on a user's wall using the access token we saved earlier:
IQueryable<FacebookDeliveryQueue> toSend = objectContext.FacebookDeliveryQueues.Where(p => !p.IsDelivered);
foreach (FacebookDeliveryQueue facebookDeliveryQueueItem in toSend)
{
string facebookAccessToken = facebookDeliveryQueueItem.Cart.FacebookAccessToken;
string facebookRecipientId = facebookDeliveryQueueItem.Cart.FacebookRecipientId;
var client = new FacebookClient(facebookAccessToken);
dynamic parameters = new ExpandoObject();
parameters.message = facebookDeliveryQueueItem.Cart.CustomMessageBody;
client.Post(facebookRecipientId + "/feed", parameters);
}
My problem is, this ONLY works with access tokens from the user that created the facebook application. E.g.
Success:
I, the creator of this application, log in and pick one of my friends to send a message to, this info is saved to the database, the service runs, my message is posted to my friend's wall.
Failure:
I log in on my dummy test account (approving the app permissions on this account), pick one of my dummy test account's friend, this info is saved to the database, the service runs and throws an invalid access token error.
Any ideas why?
Update: Switched to Oauth login -- no change. Still getting "(OAuthException) Invalid access token signature." when attempting to post to friend's wall.
Looks like you're using facebook's old login methods, which they recently just turned off, so your old access tokens aren't valid anymore? And your javascript isn't generating the right kind of token. Read the latest version of the FB.login documentation for more info on what changes you need to make. Specifically,
pass oauth: true to the FB.init call
check for response.authResponse instead of response.session now.
Also, check that your app isn't in "sandbox mode". Go to the app settings page and click on "advanced". Sandbox mode makes it so that only developers can use the app.
The persistence to the database was silently trimming the access token to 75 characters, which in the case of my own user, was enough (small user id because it's an old account) -- but five characters too short in the case of my test account which has a very large user id.
Woops.

Facebook access token problem

I am connecting to login facebook page through an url. I receive the access token in my application and i can prints all my contacts from the list. I have a problem: there are times when i do receive the access token and if i logout from facebook and rebuild my application the second time , i don't have any access token. WHY? If i wait i guess 10-15 minutes and try again it works. How to resolve this? THX
I am using the auth url. THe following link was my example link:
http://geekdeck.com/vb-net-facebook-get-access-token-for-desktop-application/
EDIT:
I have the following code:
browserFacebook.Navigate(#"https://graph.facebook.com/oauth/authorize?client_id="+ FacebookApplicationID + "&redirect_uri=http://www.facebook.com/connect/login_success.html&type=user_agent&display=popup");
string someString = browserFacebook.Url.ToString();
This returns something like the following:
"http://www.facebook.com/connect/login_success.html#access_token=ACCESS TOKEN.expires_in=0"
I can then easily use this access token with the Graph API to access an users facebook details as in the following code:
Facebook.FacebookGraphAPI g = new FacebookGraphAPI("ACCESS_TOKEN");
var fbUser = g.GetObject("me", null);
PROBLEM:
When I rebuild the application, the link that i receive is OpenDNS (or navigation to the webpage was canceled) and I have to access token. Why? How can I resolve this error? After a a while 1-2 hours I receive again the token.
"https://graph.facebook.com/oauth/authorize?client_id=" +
FacebookApplicationID +
"&redirect_uri=http://www.facebook.com/connect/login_success.html&type=user_agent&display=popup");

Categories

Resources