Get Facebook C# Api Access Token


 Get Facebook C# Api Access Token  
 

Facebook team launched Facebook API client in c#, but this library doesn’t give any functionality to Receive the access token for the API which is required to request authenticated information of a user. So, c# developers of Facebook api can use this library only for public information retrieval and need to implement their own ways to retrieve the access token before requesting authenticated information. To make this process a little easier for beginners in Facebook platform, I am going to illustrate an easy way to retrieve the Facebook c# API access token here with code examples and step by step instructions:

When We Need this Access Token?

I am assuming that, you already know about registering a new Facebook application. After registering you will receive few codes named ‘App ID’,’API Key’ and ‘App Secret’ . With these, you will be able to start using Facebook API and make call to Facebook API for any kind of public data. You will need to get the access token only when you intend to access some private data for a user. Then, user will have to allow your application for the usage, what will give you the access to his private data, access token is the key to that door.

Optional Customized Facebook Class:

Here I am going to make use of my two custom class, one is MYWebRequest, that I have discussed before while showing way of creating http request using c sharp; Another is MyFB, a simple class that utilizes Facebook C# API library and meet my custom needs :)

You can get the code snippet of MyWebRequest class from the related post linked above, and here is the code sample for the MyFB class, which you can also use by enhancing/extending for your custom needs:

public class MyFB
    {
        private FacebookAPI myFBAPI;
        private string appId;
        private string apiKey;
        private string appSecret;

#region Application Settings Properties
        /// <summary>
        /// Get And Set Application ID
        /// </summary>
        public String ApplicationID
        {
            get 
            {
                return appId;
            }
            set
            {
                appId = value;
            }
        }

        /// <summary>
        /// Get And Set API Key
        /// </summary>
        public String APIKey
        {
            get
            {
                return apiKey;
            }
            set
            {
                apiKey = value;
            }
        }

        /// <summary>
        /// Get And Set Application Secret
        /// </summary>
        public String ApplicationSecret
        {
            get
            {
                return appSecret;
            }
            set
            {
                appSecret = value;
            }
        }

        /// <summary>
        /// Get And Set Access Token
        /// </summary>
        public String AccessToken
        {
            get
            {
                return myFBAPI.AccessToken;
            }
            set
            {
                myFBAPI.AccessToken = value;
            }
        }
#endregion

        //Constructor        
        public MyFB()
        {            
            myFBAPI = new FacebookAPI();          
        }

        public String GetMyName()
        {
            try
            {
                JSONObject me = myFBAPI.Get("/me");
                return me.Dictionary["name"].String;
            }
            catch(FacebookAPIException err)
            {
                return err.Message;
            }
        }

        public String GetAccessToken(string code)
        {
            //create the constructor with post type and few data
            MyWebRequest myRequest = new MyWebRequest("https://graph.facebook.com/oauth/access_token", "GET", "client_id=" + this.ApplicationID + "&client_secret=" + this.ApplicationSecret + "&code=" + code + "&redirect_uri=http:%2F%2Flocalhost:5176%2F");

            string accessToken = myRequest.GetResponse().Split('&')[0];
            accessToken = accessToken.Split('=')[1];

            return accessToken;
        }

    }

Redirect to Facebook to allow access:

To allow access, Facebook requires that you redirect the user to the Facebook page(given of Facebook API documentation) where user is asked to allow his private information access to the application. And then return back to the application with a reply code, which is later can be used to retrieve the access token.

(My code here is from a sample asp.net MVC application’s controller function. Make the tweak to fit to yours if you are using other type of application. Also, I have tested the application on my local visual studio asp.net server, for which i am using local host as my application domain, you should change that to your domain.)

 var settings = ConfigurationManager.GetSection("facebookSettings");
            MySettings current;
            string apiKey;
            if (settings != null)
            {
                current = settings as MySettings;
                 apiKey = current.ApiKey;
            }
            
           // ViewData["ApiKey"] = ConfigurationManager.AppSettings["FBAppSecret"];

            string code = Request.QueryString["code"];
            string appId = WebConfigurationManager.AppSettings["FBAppID"];
            string appSecret = WebConfigurationManager.AppSettings["FBAppSecret"];
           
            if (code == "" || code == null)
            {
                //request for authentication
                Response.Redirect("https://graph.facebook.com/oauth/authorize?client_id=" + appId + "&redirect_uri=http://localhost:5176/");
            }
            else
            {                
                fb = new MyFB();
                fb.ApplicationSecret = appSecret;
                fb.ApplicationID = appId;
                string accessToken = fb.GetAccessToken(code);
                fb.AccessToken = accessToken;              
                            
                ViewData["MyName"] = fb.GetMyName();                
            }

Here, on the above code sample, structure of MySettings class is being created from the idea of my another article on storing application settings using c#, so either go through that to get the clear idea and use the best practice, or you can hard code the settings value for now for testing quickly. First we are checking the for the ‘code’ variable value from the uri string as after returning from Facebook authentication, it redirects to our given URL with added the code as part of the URL.Initially, when application started to launch its empty, so ‘code’ value will be null and the if condition will become true, and then application will redirect the user to the Facebook oauth URL for permission to grant access.

Last One More Internal Request To Facebook:

After user accepts and allows the application to access private data, application will redirect including the code value, this time that value will be valid non null and else block will be executed. There all settings are served to the MyFB class instance and ‘GetAccessToken’ method is being called , which in turns create a GET Request to Facebook along with the code value for an access token, then facebook returns a string containing the access token and its expiation duration. By parsing that string the method return the access token(it can also be set directly to the class’s access token variable instead of returning, just doing it if you are interested to use it with some other class’s also). After it, we are set up completely to make the authenticated requests. Here I have used the simple ‘/me’ request and from the result, the user’s name is being shown.

Note For Desktop Application Developers:

If you are creating .NET desktop application using facebook API, you will have to do things a little differently. Please, read the official facebook notes for desktop application authentication. Also, you will have to be familiar with WebBrowser For WPF or WebBrowser For Windows Forms , depends on which desktop type application you are creating. Basically, you will need to pass 2 more parameter in the URL when pop-up the url in your application with WebBrowser control, which are “type=user_agent&display=popup” that will directly send the access token back without need of another extra request that is needed in web application.

Hope this tutorial will help you to get started with, let me know by commenting if you have any questions. Also, to know more about facebook c#, please read my another article about getting started with facebook graph api in c# . Happy coding :)

Comments

  1. ProudGeekDad says

    Hi Rana. Thanks for putting together this article. I’ve researched a few ways to integrate Facebook within my web site, and I feel that going that going with the Facebook C# API is the way to go.

    Unfortunately, I’ve come across a problem that I haven’t been able to figure out.
    I’ve implemented your MyWebRequest class and when I hit the line

    dataStream = request.GetRequestStream();

    I receive a ProtocolViolationException with the message “Cannot send a content-body with this verb-type”.

    Any ideas?

  2. says

    Can you please share your line of code that you are using while making the mywebrequest class please? Was it seen as a valid url while debugging? Also, have you tried that url directly in the browser what it returns? For valid url, the returned respose should include a valid access token and expiration timestamp.

  3. ProudGeekDad says

    I ended up changing this line:

    dataStream = request.GetRequestStream();

    to this:

    dataStream = request.GetResponse().GetResponseStream();

    I’m not receiving the ProtocolViolationException error any more, but I am receiving a 400 error from Facebook’s server. I think that’s an improvement, but not 100% sure yet.

  4. suppu says

    i am trying your solution but System.Net.WebException: The operation has timed out error is coming how to solve that.

    • says

      Debug what url is generating for making the web request. try that on your browser whether that shows a access token and expiration time info.

  5. Tudor says

    Hello,

    Where can I find a list of parameters? For instance, I call

    JSONObject f = faceApi.Get(“/me/friends”);

    to retrieve my friends, but what about if I want my statuses? or my friend’s statuses? Is there any available list of commands?

    Tudor

  6. Inge says

    I am wondering if the following is possible or not! hope someone can help!

    From a particular website page I would like to offer a log in with your facebook account. After the ‘allowing’ I would like to redirect that person to the webpage where he came from (read this can be from hundreds of different pages). Would it be possible to redirect to the starting webpage after the authentification?

    Hope someone has an awnser!

    Thnx !!!

  7. says

    Hi I am having a problem.

    I have added Facebook.dll api along with facebook.web.dll, facebook.web.mvc.dll

    but for FacebookAPI it is missing the reference and also for FacebookAPI(); JSONObject, FacebookAPIException

    So how can u add up reference to these ???

  8. says

    How we can call method below you described.
    public String GetAccessToken(string code)
    {}

    I want to know what string code should we pass..please give example.

  9. Khumesh Kumawat says

    Hi…

    I want to create a service using c# for getting access token social login provider like facebook, twitter etc and i want to check login status of every login provider by service every 5 minutes. Plz tell me solution for this.

    Thanks
    Khumesh Kumawat

  10. says

    I am facing several problems trying to implement the facebook access code. I am allowed access to my app, but I can’t get passed the fb.getaccesstoken function. It gives me this error:

    Cannot send a content-body with this verb-type.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.

    Source Error:

    Line 62:
    Line 63: // Get the request stream.
    Line 64: dataStream = request.GetRequestStream();
    Line 65:
    Line 66: // Write the data to the request stream.

  11. devin says

    @author
    thanks a ton mate!

    @Fernando Linhares
    you have the code that fb sends you but using that you are not able to get the access token. is that the case? if so, the following might help you.

    //catch the code sent by fb
    var fb_code = Request.QueryString["code"];

    if (fb_code != null)
    {
    string GraphURL = “https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL& client_secret=YOUR_APP_SECRET&code=” + fb_code;
    WebRequest request = WebRequest.Create(GraphURL);
    request.Method = “GET”;
    WebResponse response = request.GetResponse();
    Stream dataStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(dataStream);
    string responseFromServer = reader.ReadToEnd();

    reader.Close();
    dataStream.Close();
    response.Close();
    }

    now, the responseFromServer will contain the access token. you can split it and fetch it!

  12. Rodrigo says

    Everytime I want to get a user info, I have to do the request?

    Otherthing, how do you handle the access_token expiration?

    By the way, good post you got there!

    • says

      hi, you can set the expiration time yourself, even to infinity. Checkout the facebook official api page references for details. Thanks.

  13. en says

    i have this error:
    Server Error in ‘/’ Application.

    Cannot send a content-body with this verb-type.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.

    Source Error:

    Line 56: request.ContentType = “application/x-www-form-urlencoded”;
    Line 57: request.ContentLength = byteArray.Length;
    Line 58: dataStream = request.GetRequestStream();
    Line 59:
    Line 60:
    could you tell me what is the problem??

  14. en says

    this is the code of webrequest..i had alreadt written it…
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Configuration;
    using System.Data.SqlClient;
    using System.Data;
    using Facebook;
    using System.Net;
    using System.IO;
    using System.Text;

    namespace SocialLikeGraphSharp
    {
    public class MyWebRequest
    {
    private WebRequest request;
    private Stream dataStream;

    private string status;

    public String Status
    {
    get
    {
    return status;
    }
    set
    {
    status = value;
    }
    }
    public MyWebRequest(string url)
    {
    request = WebRequest.Create(url);
    }
    public MyWebRequest(string url, string method)
    : this(url)
    {
    if (method.Equals(“GET”) || method.Equals(“POST”))
    {
    request.Method = method;
    }
    else
    {
    throw new Exception(“Invalid Method Type”);
    }
    }
    public MyWebRequest(string url, string method, string data)
    : this(url, method)
    {
    string postData = data;
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    request.Method = “POST”;

    request.ContentType = “application/x-www-form-urlencoded”;
    request.ContentLength = byteArray.Length;
    dataStream = request.GetRequestStream();

    dataStream.Write(byteArray, 0, byteArray.Length);
    dataStream.Close();

    }
    public string GetResponse()
    {

    //request.Credentials = CredentialCache.DefaultCredentials;
    WebResponse response = request.GetResponse();

    this.Status = ((HttpWebResponse)response).StatusDescription;
    dataStream = response.GetResponseStream();

    StreamReader reader = new StreamReader(dataStream);

    string responseFromServer = reader.ReadToEnd();

    reader.Close();
    dataStream.Close();
    response.Close();

    return responseFromServer;

    }

    • says

      Hi, to achieve this, you will just have to get extended permission, which doesn’t have any expiration time. This will give you access even when user is offline. Please refer to “For how long you want user to authenticate” section on my another article regarding guidelines on facebook authentication . Hope it helps. Thanks.

    • says

      Hi, I didn’t work on any desktop application based on facebook sdk. But, I already given hints on my last paragraph on this tutorial. Hope that helps. Also, open source project facebook sdk for c# has also few samples on desktop application as well. Hope that helps. Thanks.

      • ferose says

        I saw “user profile query” by using that we can get username,mail id,etc… but they had not mentioned anything about phone number can you pls make it clear how to get that phone number too.
        thanks for your reply in advance.

        • says

          Hello ferose, I did mention, “supported by api”- which means, if it is mentioned in api, it surely can be, if not, it can’t be. However, I did checked and found that, at the time of my writing of this tutorial and some other, it was supported, but facebook authority kept it disabled for a while. For which reason, you can’t see them on API reference. Read this announcement from facebook: http://developers.facebook.com/blog/post/447/ , where they mentioned to keep the address/phone number no longer accessible. So, I guess, you will have to live without it for now until they are enabled again, mate. Thanks.

  15. bergetburk says

    Hi,
    Where to find and download the FacebookAPI, and how do you implement that in your own code?

  16. anupavan says

    I’m trying to show a user facebook status updates on my website. I have seen the client script provided by fb suits the purpose. But my site was hosted on internet, and some of client machines may have fb blocked. so i’m trying with sdk code u r discussing. but reg authentication, offline access is not available at present. pls let me know how i overcome this authentication.

  17. says

    Help. When I do this, I put in a redirect uri of http://txttoad.com/facebookapp.aspx – and I do get the redirect uri but it looks like this.. with a # instead of the ? – what am I doing wrong

    http://txttoad.com/facebookapp.aspx#access_token=CAAEoatW79ZCIBAECZATRPD8pY5uZCb1QbjKUbrchbaZBD7IjpaBxCLYadYQevMCBj3bptDCmHL7ltOUGi748ToBRifeK6CvhZAWth8LN0oFh0jTYidkfyscn56RbrLYwcY88IElppFK0ZBZArwTB1eMzxSGlmKpoO7pwPpNJ0FkZCZCjhQimJkJvSSGve2p9MhUsQ1BN7nwbwYwZDZD&amp;expires_in=6698
    
  18. tanweer says

    Please tell me what is code. I am using in dekstop application. I just want to access token. all things are going right. app id, sceret id, redirect url. I dont what is code and where from i get this. please any body help me please

  19. says

    If I copy this url into the browser it works great – I get back the stream from my group
    https://graph.facebook.com/171486003058541/feed?access_token=long term app token]

    the response starts like this..
    {
    “data”: [
    {
    "id": "171486003058541_172666886273786",
    "from": {
    "name": "Michelle Sollicito",
    "id": "100000449886864"
    },
    "to": {
    "data": [
    {
    "name": "TxtToAd",
    "id": "171486003058541"
    }
    ]
    },

    However, if I do a get from my app the same url I do not get anything in the data object

    var request = WebRequest.Create(URL);
    request.ContentType = “application/json; charset=utf-8″;
    string text;
    var response = (HttpWebResponse)request.GetResponse();

    using (var sr = new StreamReader(response.GetResponseStream()))
    {
    text = sr.ReadToEnd();
    }

    //Response.End();
    var serializer = new JavaScriptSerializer();
    var result = serializer.Deserialize(text);
    long messages = result["data"].Length;
    Response.Write(“Messages:” + messages);

    Messages:0 is the result

    I am pretty sure this code used to work – I dont think I changed anything??
    Can anyone enlighten me?

Trackbacks

Leave a Reply