Search code examples
c#asp.net-mvcfacebook-sdk-4.0facebook-sdk-3.0

How to get current user access token from Facebook SDK in C#? Not the App access token


The below code shows to get App Access Token,

public static string GetAppAccessToken()
    {
        var fb = new FacebookClient();

        dynamic result = fb.Get("oauth/access_token", new
        {
            client_id = "****************",
            client_secret = "*******************",
            grant_type = "client_credentials"
        });

        return result.access_token;
    }

but how can I get the access token of current user who logged in using Facebook SDK's using C#?


Solution

  •     using System.Linq;
        using System.Net;
        using System.Web;
        using System.Web.Script.Serialization;
        using System.Web.UI;
        using System.Web.UI.WebControls;
        using Facebook;
        using Newtonsoft.Json;
        using Newtonsoft.Json.Linq;    
    
            public class AccessUser
            {
                public string access_token { get; set; }
                public string token_type { get; set; }
                public string expires_in { get; set; }
            }
    
            private void CheckAuthorization()
                {
                    string app_id = "**************";
                    string app_secret = "************************";
    
                    if (Request["code"] == null)
                    {
                        var redirectUrl = string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}", app_id, Request.Url.AbsoluteUri);
                        Response.Redirect(redirectUrl);
                    }
                    else
                    {
                        AccessUser au = new AccessUser();
    
                        string url = string.Format("https://graph.facebook.com/v3.2/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}", app_id, Request.Url.AbsoluteUri, app_secret, Request["code"].ToString());
    
                        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
    
                        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                        {
                            StreamReader reader = new StreamReader(response.GetResponseStream());
                            string vals = reader.ReadToEnd();
                            au = JsonConvert.DeserializeObject<AccessUser>(vals);
                            string token = au.access_token;
    
                        }
                    }
                }
    

    The above code will return the user token.

    Note: Built using aspx page and this is based on V3.2 Graph API calls. The versions like 1 and 2, we need to send the Scope in the URI.

    If anyone required source code, let me know...