我正在尝试使用Facebook作为Asp.net Identity 2.0的外部登录提供商。我在启动中有我的Facebook身份验证选项。身份验证配置为:
var facebookOptions = new FacebookAuthenticationOptions()
{
AppId = ConfigurationManager.AppSettings[OneStepCloserTo.Web.Models.Constants.FacebookClientIdKey],
AppSecret = ConfigurationManager.AppSettings[OneStepCloserTo.Web.Models.Constants.FacebookClientSecretKey]
};
facebookOptions.Scope.Add("email");
facebookOptions.Scope.Add("user_friends");
facebookOptions.Scope.Add("public_profile");
facebookOptions.Scope.Add("user_hometown");
电子邮件范围有效,因为我可以在返回的索赔中看到我的电子邮件地址。但是,此处列出的public_profile字段都不会返回。有人知道为什么会这样吗?
您无法直接从通过facebookOptions范围添加的声明中获取Facebook个人资料信息。您必须像在示例中那样添加作用域,并使用FacebookClient。
尝试使用FacebookClient
[Authorize]
public async Task<ActionResult> FacebookInfo()
{
var claimsforUser = await UserManager.GetClaimsAsync(User.Identity.GetUserId());
var access_token = claimsforUser.FirstOrDefault(x => x.Type == "FacebookAccessToken").Value;
var fb = new FacebookClient(access_token);
dynamic myInfo = fb.Get("/me/friends");
var friendsList = newList<FacebookViewModel>();
foreach (dynamic friend in myInfo.data)
{
friendsList.Add(newFacebookViewModel()
{
Name = friend.name,
ImageURL = @"https://graph.facebook.com/" + friend.id + "/picture?type=large"
});
}
return View(friendsList);
}
public class FacebookViewModel
{
[Required]
[Display(Name = "Friend's name")]
public string Name { get; set; }
public string ImageURL { get; set; }
}
参考本文
希望这能有所帮助。
您可以获得它,请参阅
var fbOptions = new FacebookAuthenticationOptions();
fbOptions.AppId = ...
fbOptions.AppSecret = ...
fbOptions.Fields.Add("email");
fbOptions.Fields.Add("first_name");
fbOptions.Fields.Add("last_name");
fbOptions.Scope.Add("public_profile");
fbOptions.Scope.Add("email");
fbOptions.Provider = new FacebookAuthenticationProvider()
{
OnAuthenticated = async context =>
{
JToken value;
if (context.User.TryGetValue("first_name", out value))
context.Identity.AddClaim(new Claim("FacebookFirstName", value.ToString()));
if (context.User.TryGetValue("last_name", out value))
context.Identity.AddClaim(new Claim("FacebookLastName", value.ToString()));
}
};