Error on Setting Authorization Header of HttpClient with Token before GetStringAsync with facebook login integration‏ RRS feed

  • Question

  • User264065878 posted

    Hi all

    I am a newbie in Facebook integration. I have tired a lot of method in getting this through however I never succeed in getting in right. it would be nice if someone could guide me on this.  I was trying to write to  a cookie  and pass it to my  authenticate in my ControlDeskController with the following code,

        propertiesHttp.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Request.Cookies["accessToken"].Value);

    it work well with the custom individual account creation. However when I integrate the facebook login (facebook doesn't not have password), it could not pass the information to the cookie. I had added a watch during the debug and found the following error

    {StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
      Pragma: no-cache
      X-SourceFiles: =?UTF-8?B?RDpcQVNQIFByb2plY3RcUHJvcGVydHlcUHJvcGVydHk0VVxUb2tlbg==?=
      Cache-Control: no-cache
      Date: Mon, 16 May 2016 15:17:41 GMT
      Server: Microsoft-IIS/10.0
      X-Powered-By: ASP.NET
      Content-Length: 34
      Content-Type: application/json; charset=UTF-8
      Expires: -1

    my code in AccountController as per below for external login, the bold code generate the error as above.
       // GET: /Account/ExternalLoginCallback
            public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
                var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
                if (loginInfo == null)
                    return RedirectToAction("Login");
            // Sign in the user with this external login provider if the user already has a login
                   var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
                   var identity = AuthenticationManager.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie);
                   var accessToken = identity.FindFirstValue("FacebookAccessToken");
                   var fb = new FacebookClient(accessToken);
                   dynamic myInfo = fb.Get("/me?fields=email"); // specify the email field
                     string email = myInfo.email;
                switch (result)
                        case SignInStatus.Success:
                        var userInfo = db.Users.Where(u => u.Email == email).Single();
                        var isConfigurationsEmpty = await db.Configurations.ToListAsync();

                        // Generate Token by Posting Request to Authenticate User Credentials
                        HttpClient clients = new HttpClient();
                        clients.BaseAddress = new Uri(GetSiteRoot());
                        var response = await clients.PostAsync("Token", new StringContent("grant_type=username=" + email, Encoding.UTF8));
                        if (response.IsSuccessStatusCode)
                            string jsonMessage;
                            using (Stream responseStream = await response.Content.ReadAsStreamAsync())
                                jsonMessage = new StreamReader(responseStream).ReadToEnd();
                            // TokenResponseModel Class to load response content
                            TokenResponseModel tokenResponse = (TokenResponseModel)JsonConvert.DeserializeObject(jsonMessage, typeof(TokenResponseModel));
                            //create cookie
                            var tokenCookie = new HttpCookie("accessToken");
                            tokenCookie.Value = tokenResponse.AccessToken;
                            return null;

                        return RedirectToLocal(returnUrl);
                        case SignInStatus.LockedOut:
                            return View("Lockout");
                        case SignInStatus.RequiresVerification:
                            return RedirectToAction("SendCode", new { ReturnUrl = returnUrl });
                         case SignInStatus.Failure:
                            // If the user does not have an account, then prompt the user to create an account
                            ViewBag.ReturnUrl = returnUrl;
                             ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                          return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });

    Greatly appreciate if someone could help me out on this

    Thank you



    Monday, May 23, 2016 3:50 PM


  • User-2057865890 posted

    Hi Bruce,

    var response = await clients.PostAsync("Token", new StringContent("grant_type=username=" + email, Encoding.UTF8));

    Consider posting entire objects/arrays through post data, you can do something like this

    var content = new StringContent(value.ToString(), Encoding.UTF8, "application/json");
    var response = await Client.PostAsync("xxx", content);

    Check this thread.

    For a complete example of using the HttpClient class, see Calling a Web API From a .NET Client

    Best Regards,


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 24, 2016 3:20 AM