Graph api, C# to share data from app to my wall - asp.net

i am trying to develop an app which can allow me to share data on Facebook wall.
For eg: consider the Facebook Canvasapp "Run with Friends". This is a canvas app using Python and Php.
https://developers.facebook.com/docs/samples/. I will be able to share data from this app to my wall./me
Before doing this v need a access token. I was able to get the authorization, accesstoken using Graph api, Oauth2.0, C#, asp.net
public string AuthorizationLinkGet(bool bUserInfo, bool bFriends, bool bfeed, bool bPhotos, bool bEvents, bool bMessages)
{
string url = string.Format("{0}?client_id={1}&redirect_uri={2}", AUTHORIZE, this.ConsumerKey, CALLBACK_URL);
if (bUserInfo == true || bFriends == true || bfeed == true || bEvents == true || bPhotos == true || bMessages == true)
{
url += "&scope=email";
if (bUserInfo == true)
{
url += ",user_about_me,user_interests,user_likes,user_location,user_notes,user_education_history,user_hometown";
}
if (bFriends == true)
{
url += ",read_friendlists,user_groups";
}
if (bfeed == true)
{
url += ",read_stream";
}
if (bEvents == true)
{
url += ",user_events";
}
if (bEvents == true)
{
url += ",user_photo_video_tags";
}
if (bMessages == true)
{
url += ",read_mailbox";
}
}
return url;
}
<add key="APIKey" value="*************************"/>
<add key="Secret" value="**********************"/>
So now how do I be able to share data from the app onto my FB wall.
I've tried Sharekit but look like Sharekit is for mobile apps.
public void AccessTokenGet(string authToken)
{
this.Token = authToken;
string accessTokenUrl = string.Format("{0}?client_id={1}&redirect_uri={2}&client_secret={3}&code={4}",
ACCESS_TOKEN, this.ConsumerKey, CALLBACK_URL, this.ConsumerSecret, authToken);
string response = WebRequest(Method.GET, accessTokenUrl, String.Empty);
if (response.Length > 0)
{
//Store the returned access_token
NameValueCollection qs = HttpUtility.ParseQueryString(response);
if (qs["access_token"] != null)
{
this.Token = qs["access_token"];
}
}
}
does any one know how to develop this canvas app in C# using Graph Api
I have no idea abt all the curls and things in Php
Also, I see people using REST, facebookservice, facebook SDK. Where would these fit it?
Thanks
Sun

Ask for the publish stream permission.
You need to POST to https://graph.facebook.com/USER_ID/feed/access_token=lerolero, posting a json like this:
{"name": "name"
"link": "http://www.link.com/",
"caption": "title",
"description": "description",
"picture": "http://www.link.com/image.jpg"}
http://developers.facebook.com/docs/reference/api/, read the publishing section, you can send a lot of other information.
Edit:
I see two possibilities.
If the facebook integration its not part of your bussiness rules (if you will not use the user information), you can just add the SHARE widget, in this case, the user will se a button, and when he click the button, the facebook authentication page will open, and when the authentication is done, the share widget will popup automatically.
If you gonna access the user information (if will be somehow attached to the user account), then, when the user clicks the button, you have to check the user account forward a facebook account, if theres not one, you have to open a authentication popup, if the user succeeds to login into facebook, the authentication popup will return you a verification code. You must exchange the verication code for a access token and attach the access token to the user account in your database. In the authentication step, you have to ask for two special permissions, the stream publish permission and the offline access permission. The first one is about the resource to publish in the user wall, and the second one its about the access token life cycle (if you dont ask for this permission, the access token will have a short life cycle, and you will need to reauthenticate the user into facebook again and again, we dont want that).
Into the code:
When the user clicks a button, call a ajax function that checks if there's a access token in the user account. If theres, return the access token (take care here, if you create a ajax that return a access tokem based on a user id, you will have a very bad security issue), if theres not, return false.
If the code returned is false, call a function that opens a popup with the facebook authentication url. In the facebook authentication popup callback url, just exchange the verification code for a access token and store it in the database. You need to keep listening the popup.closed state, to know when the process is done and call another ajax function that checks if now theres a access token in the user account or not, if not, the user just closed the popup.
If the code returned is an access token, call a ajax function that post in the user wall, its very easy, like this:
string facebookurl = "https://graph.facebook.com/me/feed?access_token=32423"
string parameters = "message=aaaa&link=bbbb";
WebRequest req = WebRequest.Create(facebookurl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
req.ContentLength = bytes.Length;
Stream stream = req.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
WebResponse res = req.GetResponse();
StreamReader streamReader = new StreamReader(res.GetResponseStream());
If you need any other piece of code, let me know.

Related

Accessing the Microsoft Graph after OpenId Connect Azure AD Callback

Fundamentally all I need to do is grab a users profile photo after successful login (asp.net 4.8) since it doesn't seem that I can request the photo to come over with the login claims.
This is the callback handler
SecurityTokenValidatedNotification<Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification
This is how I get the Identity from that callback and it's all there looking good
var identity = notification.AuthenticationTicket.Identity;
So I'm trying to callback with RestSharp
var client = new RestSharp.RestClient("https://graph.microsoft.com");
var request = new RestSharp.RestRequest($"/v1.0/users/{email}/photo/$value", RestSharp.Method.GET);
var callbackResult = client.Execute(request);
Debugger.Break();
if (callbackResult.StatusCode == HttpStatusCode.OK)
{
Debugger.Break();
}
But it keeps (I suppose OBVIOUSLY) coming back as unauthorized. Is there some token or something I can use now that the user has authenticated to add a header or querystring or something that will just get me the extra data easily?

Does the Facebook C# SDK depend on cookies on the server?

I'm using the Facebook C# SDK and am trying to figure out exactly how it works. I actually use an AJAX web method to lookup the Facebook account details based on the authenticated user ID, which looks something like this:
if (response.status === "connected")
{
KitchenPC.LogonFB(response.authResponse.userID, checkResult, facebookError);
}
On the server side, the LogonFB web method does something like:
Client = new FacebookClient(applicationId, applicationSecret);
var result = Client.Get(path) as IDictionary<string, object>;
UserId = Int64.Parse((String)result["id"]);
Name = result["name"] as String;
FirstName = result["first_name"] as String;
LastName = result["last_name"] as String;
Location = result.ContainsKey("location") ? result["location"] as String : "";
Gender = result.ContainsKey("gender") ? result["gender"] as String : "";
Email = result["email"] as String;
Where path is the user ID passed in from the client.
My Question:
I'm switching from ASP.NET Web Service to WCF, and WCF does not support cookies. In fact, HttpContext.Current will be null within the WCF pipeline. I was under the impression that the Facebook C# SDK depended on the fbm_ and fmsr_ cookies being passed in on the request, which would be used to validate the session with the Facebook server. However, much to my surprise, the .Get() call still works, and user information is returned. I also dug through the SDK source code and nowhere in it do I find references to HttpContext.Current.
Does the Facebook C# SDK work completely independently of cookies? Does this mean that all I need is the user's Facebook ID, and as long as they've previously approved my app ID, I can grab information about their account?
I just want to make sure I'm not doing anything wrong, and I'm not going to run into trouble in production.
When you pass the constructor with appId and appSecret, it will auto set the access token as app access token using string.Concat(appId, '|', appSecret). That constructor has been removed in newer version of the sdk. https://github.com/facebook-csharp-sdk/facebook-csharp-sdk/issues/103
Set it to null if you don't want the access token.
Client = new FacebookClient(applicationId, applicationSecret);
Client.AccessToken = null;
var result = Client.Get(path) as IDictionary<string, object>;

User Authentication in ASP.NET when authentication is checked by javascript functions

Please suggest or change some suitlable title for this question as i am not able to find one
I am using Facebook to allow the users to authenticate to my site.
I use Facebook Login Button and somehow i find out the user is authenticated or not.
I am developing my website in ASP.NET 4.0
I check whether the user is authenticate through Javascript.
The problem is how should i tell my server that this user is authenticated and assign some ASP.NET roles. I cannot use Ajax becuase of securoty reasons and might be a attack of Impersonation. This site may have transactions in the future so it need to be less security vunerable.
RIght now what i did is create a session using javascript and redirect to some other page and then assign roles but i am not statisfied with this method
Any help is appreciated.
The easiest way would be to use Page methods and Page methods call your service on server or authenticate directly.
http://www.geekzilla.co.uk/View7B75C93E-C8C9-4576-972B-2C3138DFC671.htm
To fix this, after facebook successfully authenticate the user i postback the website with the some arguments.
FB.api('/me', function (response) {
res_id = (response.id);
__doPostBack('SetSessionVariable', res_id + "$" + response.first_name + "$"+ response.last_name);
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
});
And in code i do :
string eventTarget = (this.Request["__EVENTTARGET"] == null) ? string.Empty : this.Request["__EVENTTARGET"];
string eventArgument = (this.Request["__EVENTARGUMENT"] == null) ? string.Empty : this.Request["__EVENTARGUMENT"];
if (eventTarget == "SetSessionVariable")
{
// Authenticate User
}

Facebook Connect and ASP.NET

I'm at step 8 of the authentication overview found here: http://wiki.developers.facebook.com/index.php/How_Connect_Authentication_Works
In particular, the user has logged into facebook via Facebook Connect and their web session has been created. How do I use the facebook developer toolkit v2.0 (from clarity) to retrieve information about the user. For example, I'd like to get the user's first name and last name.
Examples in the documentation are geared towards facebook applications, which this is not.
Update
Facebook recently released the Graph API. Unless you are maintaining an application that is using Facebook Connect, you should check out the latest API: http://developers.facebook.com/docs/
I had a lot of trouble figuring out how to make server side calls once a user logged in with Facebook Connect. The key is that the Facebook Connect javascript sets cookies on the client once there's a successful login. You use the values of these cookies to perform API calls on the server.
The confusing part was looking at the PHP sample they released. Their server side API automatically takes care of reading these cookie values and setting up an API object that's ready to make requests on behalf of the logged in user.
Here's an example using the Facebook Toolkit on the server after the user has logged in with Facebook Connect.
Server code:
API api = new API();
api.ApplicationKey = Utility.ApiKey();
api.SessionKey = Utility.SessionKey();
api.Secret = Utility.SecretKey();
api.uid = Utility.GetUserID();
facebook.Schema.user user = api.users.getInfo();
string fullName = user.first_name + " " + user.last_name;
foreach (facebook.Schema.user friend in api.friends.getUserObjects())
{
// do something with the friend
}
Utility.cs
public static class Utility
{
public static string ApiKey()
{
return ConfigurationManager.AppSettings["Facebook.API_Key"];
}
public static string SecretKey()
{
return ConfigurationManager.AppSettings["Facebook.Secret_Key"];
}
public static string SessionKey()
{
return GetFacebookCookie("session_key");
}
public static int GetUserID()
{
return int.Parse(GetFacebookCookie("user"));
}
private static string GetFacebookCookie(string name)
{
if (HttpContext.Current == null)
throw new ApplicationException("HttpContext cannot be null.");
string fullName = ApiKey() + "_" + name;
if (HttpContext.Current.Request.Cookies[fullName] == null)
throw new ApplicationException("Could not find facebook cookie named " + fullName);
return HttpContext.Current.Request.Cookies[fullName].Value;
}
}
I followed up on this concept and wrote a full fledged article that solves this problem in ASP.NET. Please see the following.
How to Retrieve User Data from Facebook Connect in ASP.NET - Devtacular
Thanks to Calebt for a good start on that helper class.
Enjoy.
Facebook Connect actually isn't too difficult, there's just a lack of documentation.
Put the necessary javascript from here: http://tinyurl.com/5527og
Validate the cookies match the signature provided by facebook to prevent hacking, see: http://tinyurl.com/57ry3s for an explanation on how to get started
Create an api object (Facebook.API.FacebookAPI)
On the api object, set the application key and secret Facebook provides you when you create your app.
Set api.SessionKey and api.UserId from the cookies created for you from facebook connect.
Once that is done, you can start making calls to facebook:
Facebook.Entity.User user = api.GetUserInfo(); //will get you started with the authenticated person
This is missing from the answers listed so far:
After login is successful, Facebook recommends that you validate the cookies are in fact legit and placed on the client machine by them.
Here is two methods that can be used together to solve this. You might want to add the IsValidFacebookSignature method to calebt's Utility class. Notice I have changed his GetFacebookCookie method slightly as well.
private bool IsValidFacebookSignature()
{
//keys must remain in alphabetical order
string[] keyArray = { "expires", "session_key", "ss", "user" };
string signature = "";
foreach (string key in keyArray)
signature += string.Format("{0}={1}", key, GetFacebookCookie(key));
signature += SecretKey; //your secret key issued by FB
MD5 md5 = MD5.Create();
byte[] hash = md5.ComputeHash(Encoding.UTF8.GetBytes(signature.Trim()));
StringBuilder sb = new StringBuilder();
foreach (byte hashByte in hash)
sb.Append(hashByte.ToString("x2", CultureInfo.InvariantCulture));
return (GetFacebookCookie("") == sb.ToString());
}
private string GetFacebookCookie(string cookieName)
{
//APIKey issued by FB
string fullCookie = string.IsNullOrEmpty(cookieName) ? ApiKey : ApiKey + "_" + cookieName;
return Request.Cookies[fullCookie].Value;
}
The SecretKey and ApiKey are values provided to you by Facebook. In this case these values need to be set, preferably coming from the .config file.
I followed up from Bill's great article, and made this little component. It takes care of identifying and validating the user from the Facebook Connect cookies.
Facebook Connect Authentication for ASP.NET
I hope that helps somebody!
Cheers,
Adam
You may also use SocialAuth.NET
It provides authentication, profiles and contacts with facebook, google, MSN and Yahoo with little development effort.
My two cents: a very simple project utilizing the "login with Facebook" feature - facebooklogin.codeplex.com
Not a library, but shows how it all works.

Using Custom MembershipProvider without a Login control in ASP.NET

We have got a custom MembershipProvider in ASP.NET. Now there are 2 possible scenario the user can be validated:
User login via login.aspx page by entering his username/password. I have used Login control and linked it with the MyMembershipProvider. This is working perfectly fine.
An authentication token is passed via some URL in query string form a different web sites. For this I have one overload in MembershipProvider.Validate(string authenticationToken), which is actually validating the user. In this case we cannot use the Login control. Now how can I use the same MembershipProvider to validate the user without actually using the Login control? I tried to call Validate manually, but this is not signing the user in.
Here is the code snippet I am using
if (!string.IsNullOrEmpty(Request.QueryString["authenticationToken"])) {
string ticket = Request.QueryString["authenticationToken"];
MyMembershipProvider provider = Membership.Provider as MyMembershipProvider;
if (provider != null) {
if (provider.ValidateUser(ticket))
// Login Success
else
// Login Fail
}
}
After validation is successful, you need to sign in the user, by calling FormsAuthentication.Authenticate: http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.authenticate.aspx
EDIT: It is FormsAuthentication.SetAuthCookie:
http://msdn.microsoft.com/en-us/library/twk5762b.aspx
Also, to redirect the user back where he wanted to go, call: FormsAuthentication.RedirectFromLoginPage: http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.redirectfromloginpage.aspx
link text
You can set your own FormsAuthenticationTicket if the validation is successful.
Something like this;
if (provider != null) {
if (provider.ValidateUser(ticket)) {
// Login Success
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1, //version
someUserName, //name
DateTime.Now, //issue date
DateTime.Now.AddMinutes(lengthOfSession), //expiration
false, // persistence of login
FormsAuthentication.FormsCookiePath
);
//encrypt the ticket
string hash = FormsAuthentication.Encrypt(authTicket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
Response.Cookies.Add(cookie);
Response.Redirect(url where you want the user to land);
} else {
// Login Fail
}
}
You are right in the case of storing the auth information as a cookie directly. But using a strong hash function (e.g. MD5 + SHA1) is great and secure.
By the way, if you use sessions (which is also just a hash cookie) you could attach auth information to it.

Resources