Decode Signed Request Without Authentication - c#

Are we able to use the Facebook C# SDK to decode the signed_request parameter that is passed to the Facebook Tab page, without using Authentication? Basically, I am looking for a way to decode and parse the page JSON object that the signed_request contains.
I am looking for the .NET C# equivelent to accomplishing the same type of decode in this PHP example: Seamless way to check if user likes page

I am just pasting same answer I have answered in another post.
Fans-only content in facebook with asp.net C# sdk
You get signed request when your web page is loaded within facebook canvas app; you should be able to parse signed request something similar to following:
if (Request.Params["signed_request"] != null)
{
string payload = Request.Params["signed_request"].Split('.')[1];
var encoding = new UTF8Encoding();
var decodedJson = payload.Replace("=", string.Empty).Replace('-', '+').Replace('_', '/');
var base64JsonArray = Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length + (4 - decodedJson.Length % 4) % 4, '='));
var json = encoding.GetString(base64JsonArray);
var o = JObject.Parse(json);
var lPid = Convert.ToString(o.SelectToken("page.id")).Replace("\"", "");
var lLiked = Convert.ToString(o.SelectToken("page.liked")).Replace("\"", "");
var lUserId= Convert.ToString(o.SelectToken("user_id")).Replace("\"", "");
}
You need to add reference to json libraries in order to parse signed requestin C#, download from http://json.codeplex.com/
Also refere to How to decode OAuth 2.0 for Canvas signed_request in C#? if you are worndering about signed request.

What do you mean 'without authentication'? The signed request is signed with your app secret, so you can decode it regardless of whether the current user has authorised your app
{edit} I now realise you're referring to a library named Authentication{/edit}
If you find another library or reimplement the algorithm for HMAC SHA-256 and a base64url decoder i'm sure you could do it without using that specific library, but it's probably easier to just use it

Related

How do you decode/decrypt a SignedCMS/PKCS#7 in C# PCL

So, I have an WebAPI that is returning a PKCS#7 file to a client. The client is written as a C# PCL so it can be used in Xamarin iOS and Android projects.
My initial tests worked fine because I was encoding and decoding in my unit tests and could use the Pkcs library. It seems I can't find any way of decoding the data on the client because I don't know of any Pkcs library that works with a PCL.
Can someone tell me how/if this can be done?
So, I did end up switching my project to .netstandard 1.4 and using Portable.BouncyCastle to decode the Cms created on the server side.
Here is the code that I used to decode the Cms. I'm sort of trusting that this is also checking the signature since there is no explicit method for doing that in BouncyCastle like there is via the framework code i.e. CheckSignature().
var cmsParser = new Org.BouncyCastle.Cms.CmsSignedDataParser(dataBytes);
var cmsSignedContent = cmsParser.GetSignedContent();
var contentStream = cmsSignedContent.ContentStream;
var memoryStream = new MemoryStream();
contentStream.CopyTo(memoryStream);
byte[] contentBytes = memoryStream.ToArray();
var decodedContent = Encoding.UTF8.GetString(contentBytes);
In addition I added this to verify the signer info:
cmsParser.GetSignedContent().Drain();
var certStore = cmsParser.GetCertificates("Collection");
var signerInfos = cmsParser.GetSignerInfos();
var signers = signerInfos.GetSigners();
foreach (SignerInformation signer in signers)
{
var certCollection = certStore.GetMatches(signer.SignerID);
foreach (Org.BouncyCastle.X509.X509Certificate cert in certCollection)
{
var result = signer.Verify(cert);
if (!result)
{
throw new Exception("Certificate verification error, the signer could not be verified.");
}
}
}
I'm not 100% sure if this is all I need to do but my client's will communicate via SSL and they are using an HMAC auth with an appId and client secret so I'm not so concerned with in transit issues. I'm basically transferring a "license" file and I want to make sure the contents are not tampered with after it has been saved on the client device.
If anyone has any suggestions or concerns with this please let me know.
Thanks.
I currently use PCLCrypto to encrypt and decrypt using PKCS#7 on the client (in a Xamarin Forms project). I assume it will do what you need as well.
The PKCS#7 wiki example can be found here

Facebook page /feed missing images

I was using the Facebook Public API Feed for the longest time and since they deprecated it I've been trying to find a replacement method in C#.
I am able to get my page posts but any post that contains images I only get the message and no images. After spending the past weekend trying to find a way I am desperate to know if anyone has had any success in getting full page post content from the Facebook C# SDK library.
Here is what I have and it works for getting the posts but they do not contain any images.
var fb = new FacebookClient
{
AppId = ConfigurationManager.AppSettings.Get("FacebookAppID"),
AppSecret = ConfigurationManager.AppSettings.Get("FacebookAppSecret"),
AccessToken = ConfigurationManager.AppSettings.Get("FacebookAccessToken")
};
var pageFeed = string.Format("/v2.4/{0}/feed", _facebookPageId);
dynamic response = fb.Get(pageFeed);
Since the upgrade in Graph API v2.4. Only a limited set of data is sent via FB unless specifically requested. You should pass the fields parameter with the keyword of data which you would like to retrieve.
A list of keyword is available here
In your case, the request statement would be:
var pageFeed = string.Format("/v2.4/{0}/feed?fields=id,message,picture", _facebookPageId);
To get all pictures from a post: replace picture with attachments, as picture will return the very first picture linked to the post.
var pageFeed = string.Format("/v2.4/{0}/feed?fields=id,message,attachments", _facebookPageId);

Decrypting forms authentication token (AES, SHA1) in node js

Has anyone had luck decrypting a .NET forms authentication generated cookie in node js using the crypto library?
I'm using AES for encryption and SHA1 for validation in .NET forms authentication mechanism.
I was wondering if someone had this problem before and solved it?
I played with this and made the following code for Node.js:
var crypto = require('crypto');
var iconv = require('iconv-lite');
function hash(password) {
// your validation key from web.config + 00 at the end
var buf = new Buffer('...00', 'hex');
var hmac = crypto.createHmac('sha1', buf);
// convert password from utf8 to UTF16
var pass = iconv.encode(password, 'utf16le');
hmac.update(pass);
return hmac.digest('base64');
}
console.log(hash('test'));
Use it to compare hashes from your database.
It depends on web.config settings.
You can see the source code of Encryp and Decrypt here with all the different possibilities (Framework20SP1, Framework20SP2, etc)
https://github.com/Microsoft/referencesource/blob/master/System.Web/Security/FormsAuthentication.cs
For example, on Framework20SP1 the cookie looks like: Enc(IV+SerializedTicket+Modifier)+HMAC(Enc(IV+SerializedTicket+Modifier))

Facebook Retrive Data using Graph API using c#

i have created desktop Facebook application using c# .net. i want to retrieve users message,post and chat history. which is convenient way to retrieve users all information.i have started with Facebook Graph API but i am not getting any example.
can any one help me ?
A bit late to the party but anyway:
Add a reference to System.Net.Http and Newtonsoft.Json
string userToken = "theusertokentogiveyoumagicalpowers";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://graph.facebook.com");
HttpResponseMessage response = client.GetAsync($"me?fields=name,email&access_token={userToken}").Result;
response.EnsureSuccessStatusCode();
string result = response.Content.ReadAsStringAsync().Result;
var jsonRes = JsonConvert.DeserializeObject<dynamic>(result);
var email = jsonRes["email"].ToString();
}
Go to developer.facebook.com -> Tools & Support -> Select Graph API Explorer
Here U get FQL Query, Access Token
Then write code in C#.....
var client = new FacebookClient();
client.AccessToken = Your Access Token;
//show user's profile picture
dynamic me = client.Get("me?fields=picture");
pictureBoxProfile.Load(me.picture.data.url);
//show user's birthday
me = client.Get("me/?fields=birthday");
labelBirthday.Text = Convert.ToString(me.birthday);
http://www.codeproject.com/Articles/380635/Csharp-Application-Integration-with-Facebook-Twitt
I hope this will help you.!!!
you can check the Graph explorer tool on Developer.facebook.com , go to Tools and select graph explorer, its a nice tool which gives you exact idea about what you can fetch by sending "GET" and "POST" method on FB Graph APis
From what i see the app now only uses webhooks to post data to a data endpoint (in your app) at which point you can parse and use this. (FQL is deprecated). This is used for things like messaging.
A get request can be send to the API to get info - like the amt. of likes on your page.
The docs of FB explain the string you have to send pretty nicely. Sending requests can be done with the webclient, or your own webrequests.
https://msdn.microsoft.com/en-us/library/bay1b5dh(v=vs.110).aspx
Then once you have a string of the JSON formatted page you can parse this using JSON.NET library. It's available as a NUGEt package.

Invoke Google Maps API V3 Javascript API from Windows Forms app?

Google has this fine new Google Maps API v3 which is a "Javascript API".
Is there any possibility to invoke this API from a Windows Forms application written in Visual C# .net 3.5?
EDIT:
The goal is to convert addresses to lat/long format using the Google Maps Geocoder.
EDIT 2:
I'd like to use v3 of the API as it doesn't require an API key anymore. API keys should be bound to a webserver which can't be the case for a Windows Forms app.
Edit: Looks like the api key is no longer required.
You can use the REST APIs and parse the response (XML/JSON/CSV).
http://maps.google.com/maps/geo?q=State+St,+Troy,+NY&output=csv&oe=utf8&sensor=false
Would output:
200,6,42.730070,-73.690570
Which is:
200 - G_GEO_SUCCESS
6 - Street level accuracy
42.730070 - Latitude
-73.690570 - Longitude
If you are not familiar with the System.Net APIs, they would go something like this:
const string GeoCodeUrlFormat = "http://maps.google.com/maps/geo?q={0}&output=csv&oe=utf8&sensor=false";
string location = "State St, Troy, NY";
string url = String.Format(GeoCodeUrlFormat, HttpUtility.UrlEncode(location));
HttpRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
HttpResponse response = (HttpResponse)request.GetResponse(); // Can throw an exception
Stream responseStream = response.GetResponseStream();
using (StreamReader reader = new StreamReader(responseStream)
{
string firstLine = reader.ReadLine();
string[] lineParts = firstLine.Split();
GeolocationResult result = GoogleMapper.MapGeolocationResult(lineParts);
// TADA
}
Obviously there's no error handling, it doesn't support multiple return values and I haven't actually implemented MapGeolocationResult, but it should give you a start.
You could host the WebBrowser control on your form and use that to interact with the Google Maps API.
But some more information about what you are really trying to do would be nice.

Categories

Resources