Quantcast
Channel: Security
Viewing all articles
Browse latest Browse all 4737

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

$
0
0

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

<div> </div> <div>{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
}}
</div>

<div>my code in AccountController as per below for external login, the bold code generate the error as above.</div> <div></div> <div>   // GET: /Account/ExternalLoginCallback
        [AllowAnonymous]
        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;</div> <div></div> <div>            switch (result)
                {
                    case SignInStatus.Success:
                    var userInfo = db.Users.Where(u => u.Email == email).Single();
                    var isConfigurationsEmpty = await db.Configurations.ToListAsync();</div> <div></div> <div>
                    // Generate Token by Posting Request to Authenticate User Credentials
                    HttpClient clients = new HttpClient();
                    clients.BaseAddress = new Uri(GetSiteRoot());
                    clients.DefaultRequestHeaders.Accept.Clear();</div> <div> </div> <div>                   var response = await clients.PostAsync("Token", new StringContent("grant_type=username=" + email, Encoding.UTF8));</div> <div></div> <div>                    if (response.IsSuccessStatusCode)
                    {
                        string jsonMessage;
                        using (Stream responseStream = await response.Content.ReadAsStreamAsync())
                        {
                            jsonMessage = new StreamReader(responseStream).ReadToEnd();
                        }</div> <div></div> <div>                        // TokenResponseModel Class to load response content
                        TokenResponseModel tokenResponse = (TokenResponseModel)JsonConvert.DeserializeObject(jsonMessage, typeof(TokenResponseModel));</div> <div></div> <div>                        //create cookie
                        var tokenCookie = new HttpCookie("accessToken");
                        tokenCookie.Value = tokenResponse.AccessToken;
                        Response.Cookies.Add(tokenCookie);
                    }
                    else
                    {
                        return null;
                    }</div> <div></div> <div>
                    return RedirectToLocal(returnUrl);
                    case SignInStatus.LockedOut:
                        return View("Lockout");
                    case SignInStatus.RequiresVerification:
                        return RedirectToAction("SendCode", new { ReturnUrl = returnUrl });
                     case SignInStatus.Failure:
                     default:
                        // 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 });
               }
             }</div>

Greatly appreciate if someone could help me out on this

Thank you

Regards,

Bruce


Viewing all articles
Browse latest Browse all 4737

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>