I am looking at using the facebook SDK and I am wondering first what version should I be using?
It looks like some major changes are happened from 4.2 to 5(currently still in beta). Should I go ahead and use the beta? Anyone have any ides when it will be out of beta?
My second question is how can I use it for authentication.
Right now I am using DotNetOpenAuth to do all my openId authentication for my site. I am using there sort of plugin for facebook authentication(oAuth) however I am planning to use more facebook features on my site so I think it is kinda pointless to use this plugin and then the sdk libary when the library seems to be able to do it all.
Anways how do I do authentication with the sdk library. I want to have a button on my login page that they click it goes off to facebook they become authenticated and I get some request back saying that they where authenticated and then I give them a cookie and let them in.
All the tutorials I seen to have it that your just using facebook as your only authentication method but of course for me I have openId, facebook and twitter.
http://facebooksdk.codeplex.com/wikipage?title=Getting%20Started%20with%20an%20ASP.NET%20MVC%203%20Website&referringTitle=Getting%20Started
I use the Facebook SDK, and my advice for you would be to use the beta
The reason is because Facebook is changing and depreciating a lot of the Old REST interface and making Graph API the only way to access data. So, to be future proof, the latest and greatest is the way to go.
Now, it is a beta, so everything isn't 100%. If you need stability and don't mind making changes, then use the stable version and then upgrade later.
As for authentication, the process to authenticate is pretty simple.
you need your authURL:
string authURL = #"https://graph.facebook.com/oauth/authorize?client_id=" + Settings.appId + "&redirect_uri=" + redirectUrl + permissions
where appId is your Facebook Application ID (you get it when you register your app with Facebook), the redirectUrl is the URL that you want Facebook to send you the challenge token, and your permissions are the list of things you want to access with your Facebook authentication Token
You make a popup or whatever that browses to that URL. The user will login to facebook (if they haven't already) and then they will be presented with the app authorization screen (if they haven't already authorized the app). Once they authorize (or imidiately if they already authorized), the page will be forwarded to the redirectUrl that you provided. In the URL, there will be a GET variable called code that will contain the challenge string. You take that challenge code and add it as a query variable to another URL that is in the form of:
https://graph.facebook.com/oauth/access_token?client_id=YOURID&redirect_uri=http://www.facebook.com/connect/login_success.html&client_secret=YOURSECRET&code=THATCODE
That URL will return the authentication key...
Phew! That's quite the process.... If done manually :) Now that you know a little more about what's going on, you can appreciate what the SDK does for you.
To authenticate with the SDK, Just follow the 19 simple steps as outlined in this link
Easy huh?
Regarding 4.2 vs 5.0 BETA I guess you need to decide whether you want to use a BETA version or a stable version. I am sure they have a changelog in their BETA Release you can look at for the changes since the older version.
Regarding authentication using Facebook. I have a project where I support standard Forms authentication and accounts creation as well as Facebook login. In my AccountController I have one action for Forms login and one for Facebook login.
To configure the Facebook assembly you can follow the tutorial you have posted, then you can put a Facebook button on your page and similar code to begin the authentication process:
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
$(function () {
FB.init({ appId: '<%= FacebookSettings.Current.AppId %>', status: true, cookie: true, xfbml: true });
$('#fbLoginButton').click(function () {
FB.login(function (response) {
if (response.session) {
// Success - execute our facebook login action.
window.location = "<%= Url.Action("FacebookLogin", "Account") %>";
} else {
// user cancelled login or failed
}
}, { perms: 'email' });
return false;
});
});
The facebook aciton works by:
Was Facebook Authentication successful?
Do we have a user with the Facebook Id as a username in the system?
If not create a user, populate name, email, etc from the Facebook data
Set the Forms authentication cookie
Pseudo code:
FacebookApp facebook = new FacebookApp ();
if (facebook.IsAuthenticated) {
string userName = facebook.UserId.ToString();
if (UsersRepository.ByUserName(userName ) == null) {
// Create a User using the Facebook name, email, etc data
}
FormsAuthentication.SetAuthCookie (userName , true);
}
So the idea is that I delegate the authentication to those 3rd party services and then create a user on my system with the information I can fetch from them. Also in my project, because I want the user to set/very some preferences after the account is created I redirect them to the page where they can do that.
P.S: A tip regarding running your web project locally in Visual Studio. You can create a private Facebook App with "Site URL" set to e.g. "http://localhost:4911/" and use that appId. This will allow you to play with Facebook locally.
Related
Question:
I'm using a DropBox csharp API from here:
https://github.com/dkarzon/DropNet
From the Unit tests, and the only working sample from here
https://github.com/dkarzon/DropNet/blob/master/DropNet.Samples/DropNet.Samples.Web/Default.aspx.cs
I figured that it works like this:
DropNet.DropNetClient client = new DropNet.DropNetClient(strApiKey, strAppSecret);
DropNet.Models.UserLogin login = client.GetToken();
client.UserLogin = login;
var accountInfo = client.AccountInfo();
str = accountInfo.quota_info.quota.ToString();
The probem is, it throws an exception on accountinfo. (System.Net.HttpStatusCode.Unauthorized)
Everything before works fine, I get the login (usertoken & usersecret) .
I think my problem is this part of the sample application:
var url = _client.BuildAuthorizeUrl(Request.Url.ToString() + "?dropboxcallback=1");
Response.Redirect(url);
Where it redirects to dropbox for a login...
I don't have a web application, so I have no URL...
What I have is a console application, that should make a backup of my database every evening automatically as a service, for which it certainly is very bad requiring a webbrowser and a user which has to type in email/username + password.
How can I do a login by directly supplying the hardcoded username and password ?
If I use the sample application, then it works, but that requires typing in the username and password on the web, and that sucks big time for a console application...
As far as I know from other API's (facebook, google, stack exchange etc.) you'll have to redirect your user to a webpage of Dropbox, where it will grant permissions to you to use it's account to perform things.
So in general it is not possible to achive this without a webbrower. Otherwise you'll have to perform really dirty hacks to hack arround the permission system of dropbox.
Please have a look at "OAuth 2.0 authorization flow" on google.
Here's a diagram I found at Yahoo which show's how it works:
For uisng the DropnetClient's 4 argument constructor also we need to build web based url and allow the user to authenticate his account this is compusory thing, accesstoken will generate after the user hit allow button in authentication process
As GameScripting explained the Dropbox API uses oauth which requires user login through the dropbox website to authenticate the access tokens.
Checkout the documentation here: http://dkdevelopment.net/what-im-doing/dropnet/ for the 3 step process.
What sort of application are you building? Normal process is to load a browser control inside the application and navigate to the login URL with it.
Also have a look at the sample Windows Phone app to give you an idea of how this process works: https://github.com/dkarzon/DropNet/blob/master/DropNet.Samples/DropNet.Samples.WP7/MainPage.xaml.cs
Instead of hardcoding the username and password, you can hardcode the OAuth access token.
First, create a simple program (using the same app key) that follows the standard browser-based authorization flow. Then use it to authorize the app with the desired user. This will give you an OAuth access token (a "token" and "token secret") associated with that user and your app key.
Then, in your service-style application, just hardcode the OAuth access token (using DropNetClient's 4-argument constructor).
It is possible, using SharpBox - tested, works.
One needs to acquire the AccessToken as a one-time-action manually, then after that, one can omit the login page and use the saved AccessToken.
http://www.jayway.com/2012/02/06/unboxing-dropbox-and-sharpbox-2/
The magic line is:
Globals.DropBox.Token = AppLimit.CloudComputing.SharpBox.StorageProvider.DropBox.DropBoxStorageProviderTools
.ExchangeDropBoxRequestTokenIntoAccessToken(
Globals.DropBox.config
, Globals.DropBox.AppKey, Globals.DropBox.AppSec
, Globals.DropBox.requestToken
);
I have a Facebook canvas application written on asp.net mvc. I can't see what's going on in facebook.
I have client-side code that loads FB user picture:
FB.api('/' + userId, { fields: "id,link,name,picture" }, function (user) {
$('img[data-fb-user-img]', subjectVoterElement).attr('src', user.picture.data.url);
});
One day it responds picture url in user.picture, another day - in user.picture.data.url so i have errors time to time. Why FB gives different respond structure?
2.
To authorize FB user in my app i use facebook cookie being sent to my app server. Then i extract value from it, then parse the value with ParseSignedRequest method and exchange obtained code into token.
HttpCookie fbCookie = filterContext.RequestContext.HttpContext.Request.Cookies[
String.Format("fbsr_{0}", System.Configuration.ConfigurationManager.AppSettings["FB_Id"])];
string code =
((dynamic) FacebookService.FacebookService.Client.ParseSignedRequest(fbCookie.Value)).code;
using (var webClient = new WebClient())
{
var result = webClient.DownloadString(
String.Format(
"https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri=&client_secret={1}&code={2}",
FacebookService.FacebookService.Client.AppId,
FacebookService.FacebookService.Client.AppSecret,
code
)
);
Sometimes i get authorization error saying the code is expired or specified user has logged off from facebook. In fact, i logged off a hour ago and since that moment this have already been worked successfull. Also, the facebook cookie expiration time is set long enough and hasnt come yet.
Does anyone have the same problem? Thanks
I am not sure if this is the issue with #1 or not but I have had issues so I will just throw it out there. There are actually at least two different types of facebook users (could be more):
Regular facebook users that have accounts like you and me
Accounts that are just setup for a facebook page
How to create a facebook account that is just for a page?
Step 1: Logout of your facebook account
Step 2: Go here: http://www.facebook.com/pages/create.php
Step 3: Setup a page for a fake business or whatever type of page you
want to test with
Step 4: Select I do not have a facebook account and create an account
with a new email address
Now try your application with your regular user and with this facebook page only user. Like I said, I am not sure if this is your problem or not but I have had a bunch of other problem with facebook page only accounts so it is could be worth a try.
I have created an application that logs in and registers via a button click. This all works as expected by using the access token in the code behind to process the login and gain users details for prefilling some forms.
The customer has now asked for something similar to the facebook login button that puts the login/ application authentication in like a frame, rather than redirecting the user to facebook.
Looking at the documentation I am a bit puzzled on how to do this. Do the facebook login/authentication javascript buttons provide an access code for manipulation in the code behind.
Have you considered a popup login using the Facebook javascript SDK like so:
FB.ui({ method: 'auth.login',
perms: 'publish_stream',
display: 'popup' },
function (rsp) {
fg_log('on login');
if(rsp.session) {
if(rsp.perms) {
} else {
}
} else {
fg_log('No login');
}
}
);
http://developers.facebook.com/docs/reference/javascript/FB.ui/
http://developers.facebook.com/docs/reference/javascript/
The Social Plugins are self contained, and do everything client-side. You can however hook the login/logout events in the JavaScript SDK and use AJAX to talk to the server. You can also get the Facebook auth cookie server-side on subsequent requests to see if the user is logged in, which can also be validated.
Take a look Integration of Facebook and asp.net membership, for an example of setting up .Net authentication with Facebook access_token.
Basic approach that I took for my own projects are:
use facebook javascript SDK to do user login.
after login is successful, user will be able to grand their
access_token
Pass that access_token in your postback page query string (or anything suits you)
by using Graph API with Access_token from code behind you will be
able to grab user info from facebook.
then you will able to compare user info between your own user
provider and set that user as logged in
Folks, would really appreciate your help on this as maybe I'm just missing something really obvious. Basically, i'm trying to develop a Facebook canvas iframe app in C# ASP.NET that a business can install on a fan page and users can access via a tab.
Main Requirements:
1. Business clicks install which takes them to apps.facebook.com/myapp
2. I needs to check if I have record in database for that Facebook Profile
3. N: Display page where business enters a unique code. Save Profile Id and Code
4. Y: Display data from database related to that business.
The Issue:
I've created app in Facebook and created an ASP.NET website with a single page. The app is running on my dev machine under IIS. When I visit the app on Facebook, it hits my page. I retrieve and validate the signed_request with my API key. However, the decoded payload contains only the SHA256 parameter and no user, oauth, or profile data.
Is there something else I need to do or is my approach completely incorrect?
Appreciate any guidance on this.
Are you requiring user auth, doing the full handshake?
Have you enabled the "OAuth 2.0 for Canvas (beta)" migration in your Facebook app? It's the last tab of your app config.
If the user visiting your iframe inside the canvas page has not authorized your app, the payload inside the signed_request will be something like this:
{
"algorithm":"HMAC-SHA256",
"issued_at":1286824906
}
On the other hand, if your user has authorized your app, the payload inside the signed_request will be something like this:
{
"algorithm":"HMAC-SHA256",
"expires":1286827200,
"issued_at":1286821560,
"oauth_token":"Some Token",
"user_id":"Some ID"
}
Because you're missing the user_id inside the payload, it sounds like the user has not yet authorized your app.
I've integrated my website with Facebook Connect, authorization/single-sign on all working great.
Now im trying to post something to the user's wall, which im having some problems with.
First of all, im using the "old" JavaScript API (FeatureLoader.js).
These are the Graph API URL's im using:
private const string UserDetails_Url = #"https://graph.facebook.com/{0}?access_token={1}";
private const string Feed_Url = #"https://graph.facebook.com/{0}/feed?access_token={1}";
private const string TokenExchange_Url = #"https://graph.facebook.com/oauth/access_token?{0}";
I'm using the TokenExchange_Url URL to receive the unique user OAuth token to make calls with.
This is working fine, because a) i receive the token back, and b) i can issue HTTP Get Requests to the Graph API (i.e UserDetails_Url) and it works fine.
But, i cannot Post to the User's wall using the Feed_Url.
I'm pretty sure the issue is i haven't got the appropriate user permissions to post to a wall (i.e facebook-side setting).
Now, i realise i can use the fbPublish API method client-side to do this, but i want to do it server-side with the Graph API.
I wont bother showing my code which attempts the call to the Graph API to post to the user's wall, as its pretty straightforward (HttpWebRequest, set method to "POST', set content type/length, write bytes to Stream, etc).
I think the problem is i need the user to grant my aplpication "publish_stream" extended permissions.
The Facebook Graph API doco says to do this in your authorization request:
https://graph.facebook.com/oauth/authorize?
client_id=...&
redirect_uri=http://www.example.com/callback&
scope=user_photos,user_videos,publish_stream
Which confuses me because im using the following URL to get the OAuth token:
https://graph.facebook.com/oauth/access_token?bunchofqsparams
Am i using the wrong Token Exchange URL? Why is there two different URL's to seemingly get the same piece of information?
Yes - i have read the Facebook API doco (numerous times), and yes i have read other similar SO questions, but they all result in using the client-side API to publish to wall, i want to do it server side.
For the actual "Facebook Connect" button, i'm using the standard FBML:
<fb:login-button length="long" size="medium" autologoutlink="false" background="light" onlogin="facebookLogin('/login')" class=" fb_login_not_logged_in FB_login_button FB_ElementReady"><a id="RES_ID_fb_login" class="fbconnect_login_button"><img id="RES_ID_fb_login_image" src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif" alt="Connect"></a></fb:login-button>
When i click this (and not logged into Facebook), it pops up a window which the user can login. But it doesnt have the "Request Extended Permissions" dialog - shouldnt it? Or is that another popup i need to manually trigger?
So to sum up, here are my questions:
How do i grant extended permissions to publish to the user's wall?
What is the correct URL for obtaining an OAuth token?
Is there a definitive source for showing how to post to a user's wall using server-side Graph API calls?
As i presumed, i was missing a call to the client-side API to request extended permissions. (ie publish_stream).
I had a simple JavaScript function which was executed as part of the "onlogin" attribute of the FBML Login control.
Previously, i was simply doing a redirect (which would then do a single-sign-on in the server-side code).
Now, im doing this:
function postLogin(targetUrl) {
FB.Facebook.apiClient.users_hasAppPermission('publish_stream', function(result) {
if (result == 0 || result == null) {
FB.Connect.showPermissionDialog('publish_stream', function() { redirectTo(targetUrl); });
} else {
redirectTo(targetUrl);
}
});
}
Translated to english:
// On "Facebook Connect" click (which passes in a redirect URL)
// Check if user has 'publish-stream' permissions
// If they do, just redirect.
// If they dont, show a dialog requesting that permission, then redirect.
Now the server-side Graph API calls all work fine.
So to answer my own original three questions:
How do i grant extended permissions to publish to the user's wall?
Answer: make use of the client-side JavaScript API function 'FB.Connect.showPermissionDialog' to show the popup, and 'FB.Facebook.apliClient.users_hasAppPermission' to check if they have the permission.
What is the correct URL for obtaining an OAuth token?
Answer: I still believe it is "https://graph.facebook.com/oauth/access_token?{0}", but "https://graph.facebook.com/oauth/authorize?{0}" might be able to be used for a server-side authentication/authorization process.
Is there a definitive source for showing how to post to a user's wall using server-side Graph API calls?
Answer: If there was, i wouldnt have to had asked this question - so the answer in short, is no. =)
Advice to anyone starting Facebook Connect work, try to avoid the "Old JavaScript API". Do as much as you can server-side (Graph API), and only use the client-side JavaScript API for the initial handshake (cross domain receiver).