2016-03-06 91 views
0

我主要使用來自設置Facebook登錄和註冊過程的MVC應用程序中的模板。我可以註冊並使用Facebook登錄,但是當我註冊時,我想從Facebook用戶那裏獲得更多的數據(性別,生日等),所以我不必要求他們手動完成。這將在.Net中完成,所以我試圖使用Facebook .Net SDK,但我不知道如何從Visual studiio爲我設置的模板代碼中獲取用戶訪問令牌。這是我的代碼。看看var accessToken =? 「var info」有一些數據從Facebook返回,如提供者密鑰,但沒有訪問令牌或用戶標識。下面的這個方法是在用戶輸入他們的Facebook憑證之後。從Facebook SDK獲取Facebook用戶訪問令牌用於.Net的ASP.Net MVC應用程序

[HttpPost] 
    [AllowAnonymous] 
    [ValidateAntiForgeryToken] 
    public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) 
    { 
     if (User.Identity.IsAuthenticated) 
     { 
      return RedirectToAction("Index", "Manage"); 
     } 

     if (ModelState.IsValid) 
     { 
      // Get the information about the user from the external login provider 
      var info = await AuthenticationManager.GetExternalLoginInfoAsync(); 
      if (info == null) 
      { 
       return View("ExternalLoginFailure"); 
      } 
      var user = new ApplicationUser { UserName = model.UserName, Email = model.Email, MembershipCreated = DateTime.Now }; //{ UserName = model.UserName, Email = model.Email, MembershipCreated = DateTime.Now, Gender = model.Gender, Birthdate = birthdayDateTime }; 
      var result = await UserManager.CreateAsync(user); 
      if (result.Succeeded) 
      { 
       result = await UserManager.AddLoginAsync(user.Id, info.Login); 
       if (result.Succeeded) 
       { 
        await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); 

        //try to create profile here 
        var accessToken= //need to get access token here!!! 
        FacebookClient client = new FacebookClient(accessToken); 

        dynamic fbUser = client.Get("https://www.facebook.com/" + info.DefaultUserName); 

        if (returnUrl == "/Account/Register") 
        { 
         returnUrl = "/Home"; 
        } 
        return RedirectToLocal(returnUrl); 
       } 
      } 
      AddErrors(result); 
     } 

     ViewBag.ReturnUrl = returnUrl; 
     return View(model); 
    } 
+0

你如何得到令牌? – Bharat

回答

0

您可以將Facebook訪問令牌添加爲聲明。 在Startup.Auth.cs文件中添加下面的內容來將訪問令牌保存到ClaimsIdentity。

var facebookAuthenticationOptions = new FacebookAuthenticationOptions() 
      { 
       AppId = ConfigurationManager.AppSettings["Test_Facebook_AppId"], 
       AppSecret = ConfigurationManager.AppSettings["Test_Facebook_AppSecret"], 
       //SendAppSecretProof = true, 
       Provider = new FacebookAuthenticationProvider 
       { 
        OnAuthenticated = (context) => 
        { 
         context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken)); 
         return Task.FromResult(0); 
        } 
       } 
      }; 

然後,您可以從索賠身份檢索accesstoken,只要您需要它。

private async Task<UserProfile> getFacebookUserProfileInfo(string userId) 
     { 
      var claimsIdentity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie); 
      if (claimsIdentity != null) 
      { 
       var facebookAccessTokenClaim = claimsIdentity.Claims.FirstOrDefault(c => c.Type.Equals("FacebookAccessToken")); 
       if (facebookAccessTokenClaim != null) 
       { 
        var fb = new FacebookClient(facebookAccessTokenClaim.Value); 
        dynamic myInfo = fb.Get("/v2.2/me?fields=id,name,gender,about,location,link,picture.type(large)"); 
        var pictureUrl = myInfo.ContainsKey("picture") ? myInfo["picture"].data["url"] : null; 
        if (!String.IsNullOrWhiteSpace(pictureUrl)) 
        { 
         string filename = Server.MapPath(string.Format("~/Uploads/user_profile_pictures/{0}.jpeg", userId)); 

         await DownloadProfileImage(new Uri(pictureUrl),      return new UserProfile 
        { 
         Gender = myInfo.ContainsKey("gender") ? myInfo["gender"] : null, 
         FacebookPage = myInfo.ContainsKey("link") ? myInfo["link"] : null, 
         ProfilePicture = !string.IsNullOrEmpty(pictureUrl) ? string.Format("/Uploads/user_profile_pictures/{0}.jpeg", userId) : null, 
         City = myInfo.ContainsKey("location") ? myInfo["location"]["name"] : null, 
         About = myInfo.ContainsKey("about") ? myInfo["about"] : null 
        }; 
       } 
      } 
      return null; 
     }filename); 
        } 
相關問題