m4niac
m4niac

Reputation: 3

C#: Get a user access token

I'm developing a desktop application in C#.

After visiting https://www.facebook.com/dialog/oauth?client_id=123 the user logs in and the user access token is attached to the redirect uri. Its no problem, when the loginpage is displayed in a webbrowser control in my form, so i can extract the token from the url.

But this is not the way i want to get the token. My question is, is there a way to obtain the freshly created token via an Graph API call?

Because i want to display the login page in the user's standard browser and not in this embedded webbrowser. All my efforts to get the user access token have been resulted in getting the app access token, which is useless in this case.

Any hints are appreciated.

Upvotes: 0

Views: 8246

Answers (2)

Alex
Alex

Reputation: 512

// This is very raw, And Note it is a MVC3 solution, but it is in C# and I hope it helps. // It is basically a C# version of the PHP example on FB for 'Server Side Flow' // I have been at it for a while and had to go through some pain // Please note the bug I read about that states the redirect_uri must be the same for both //requests // Also read that someone had an issue if the redirect_uri did not end in '/' // Post back if you hae any ?s as I am just starting this project and am going to try and //incorporate the C# FaceBook SDK

public class AccountController : Controller
    {
        // LoginWithFaceBook
        // First Contact with FB - oauth?client_id ... redirect_uri = /Account/FacebookLinker 
        // according to a bug files on FB redirect_uri MUST BE SAME FOR both trips ( to get the 'code' then exchange the code for 'access_token'
        public ActionResult ConnectFaceBookAccount()
        {
            string APP_ID = HttpContext.Application["FacebookAppId"].ToString();
            string redirect_uri = HttpContext.Application["FacebookOAuthRedirect"].ToString();
            string state = HttpContext.Application["state_guid"].ToString();
            // in this View I simply link to this URL
            ViewBag.FaceBookOAuthUrl = "https://www.facebook.com/dialog/oauth?client_id=" + APP_ID + "&redirect_uri="+redirect_uri+"&state=" + state+"&display=popup";


            return View();
        }

        // Account/FacebookLinker
        //  redirect_uri for both getting 'code' and exchanging for 'access_token'
        public ActionResult FacebookLinker()
        {
            if (!Request.IsAuthenticated)
            {
                Response.Redirect("/Account/LogOn");
            }
            // Per FB DOC, Make sure 'state' var returned is same one you sent to reduce chance of Cross Site Forgery
            if (Request.QueryString["state"].ToString() == HttpContext.Application["state_guid"].ToString())
            {
                try
                {

                    string FBcode = Request.QueryString["code"].ToString();
                    string APP_ID = HttpContext.Application["FacebookAppId"].ToString();
                    string APP_SECRET = HttpContext.Application["FacebookAppSecret"].ToString();
                    string redirect_uri = HttpContext.Application["FacebookOAuthRedirect"].ToString();


                  string FBAccessUrl = "https://graph.facebook.com/oauth/access_token?client_id=" + APP_ID + "&redirect_uri=" + redirect_uri + "&client_secret=" + APP_SECRET + "&code=" + FBcode;


                string accessToken = null;
                // Send the request to exchange the code for access_token
                var accessTokenRequest = System.Net.HttpWebRequest.Create(FBAccessUrl);
                HttpWebResponse response = (HttpWebResponse) accessTokenRequest.GetResponse();

                 // handle response from FB 
                 // this will not be a url with params like the first request to get the 'code'
                Encoding rEncoding = Encoding.GetEncoding(response.CharacterSet);

                using(StreamReader sr = new StreamReader(response.GetResponseStream(),rEncoding))
                {
                    // parse the response to get the value of the 'access_token'
                    accessToken = HttpUtility.ParseQueryString(sr.ReadToEnd()).Get("access_token"); 
                }
                    //TODO
                    // Add to the accessToken for the Logged in User.Identity to a FBUSERS Model
                    // WHen someone Logs in Check to see if they are also in FB
                    // ON Login Page add option to login with FaceBook


                  return View();

                }
                catch (Exception exp)
                {
                    // try to get token failed

                }
            }
            else
            {
                 // state var form FB did not match state var sent

            }
            return View();
        }

Upvotes: 2

Mehmet Osmanoglu
Mehmet Osmanoglu

Reputation: 1212

I think this is achievable via URL protocol handlers;

  1. Create a custom URL protocol handler (MSDN: Registering an Application to a URL Protocol)
  2. Create a facebook page that passes user access token to your url handler (ex. myfbapp://accesstoken/{token})
  3. Set oauth redirect_uri to your facebook page
  4. Parse access token in your application

Upvotes: 0

Related Questions