Monday, November 21, 2011

Get Facebook accesstoken ASP.NET C#

A simple code sample to retrieve FB accesstoken of a FB user, using Facebook C# SDK.

Step 1:
Create a Authenticate button, on button click event build FBLoginURL with a specific return URL.
Note: your return url should match the site URL specified in your FB app settings.

Pass "scope" parameter to get required permission.
Details of scope parameters are available here https://developers.facebook.com/docs/reference/api/permissions/.

protected void btnAuthenticate_Click(object sender, EventArgs e)
{
        var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current);
        //Specify a return url, where you would like to get the access token
        oAuthClient.RedirectUri = new Uri("http://localhost:2647/default.aspx?fbRedir=1");
        var loginUri = oAuthClient.GetLoginUrl(
                                     new Dictionary
                                     {
                                         { "scope", "read_stream,publish_stream, offline_access, manage_pages" }
                                      });
         Response.Redirect(loginUri.AbsoluteUri, true);
}


Step 2:

Retrieve access token on redirect.
Note the "fbRedir" query string parameter in the redirect uri, this parameter is used to identify if the request is from facebook redirect.

On the page load event check for querystring "fbRedir" and proceed with accesstoken retrival.

protected void Page_Load(object sender, EventArgs e)
{
     if (!IsPostBack)
     {
          if (Request.QueryString["Redir"] != null && Request.QueryString["Redir"].Equals("1"))
          {
               string code = Request.QueryString["code"];
               string state = Request.QueryString["state"];
               getAuthToken(code, state);
          }
     }



private void getAuthToken(string code, string state)
{
     FacebookOAuthResult oauthResult;
     //check the result 
     if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult))
     {
          //check if authentication is successfull
          if (oauthResult.IsSuccess)
          {
               var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current);
               oAuthClient.RedirectUri = new Uri(redirectUrl);
               dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
               //Get access token
               string accessToken = tokenResult.access_token;
               //Get token expiry date (if "offline_access" not requested
               DateTime expiresOn = DateTime.MaxValue;
               if (tokenResult.ContainsKey("expires"))
               {
                    DateTimeConvertor.FromUnixTime(tokenResult.expires);
               }
               //verify access token
               FacebookClient fbClient = new FacebookClient(accessToken);
               dynamic me = fbClient.Get("me?fields=id,name");
               long facebookId = Convert.ToInt64(me.id);
          }
     }
}


Happy coding!

No comments:

Post a Comment