我正在尝试设置identityserver以便能够使用facebook登录。一切都很好,除了我无法从脸书上检索到任何用户信息。mvc应用程序应该有一个名字和姓氏声明。我已经向public_profile添加了一个作用域,但没有将其取回。
经过大量研究,我似乎需要设置一个UserService来实现这一点,但不确定如何实现。
我们将不胜感激。
以下是我在身份服务器应用程序的状态中配置外部提供商的代码:
private void ConfigureIdenityProviders (IAppBuilder app, string signInAsType)
{
var facebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions
{
AuthenticationType = "Facebook",
Caption = "Sign in with Facebook",
SignInAsAuthenticationType = signInAsType,
AppId = "xxxxxxxxxxxx",
AppSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
Provider = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationProvider()
{
OnAuthenticated = (context) =>
{
// Problem here - there is no last_name returned
JToken lastname;
if (context.User.TryGetValue("last_name", out lastname))
{
context.Identity.AddClaim(new System.Security.Claims.Claim(IdentityServer3.Core.Constants.ClaimTypes.FamilyName, lastname.ToString()));
}
context.Identity.AddClaim(new System.Security.Claims.Claim("role", "Guest"));
return Task.FromResult(0);
}
}
};
facebookOptions.Scope.Add("public_profile");
facebookOptions.Scope.Add("email");
app.UseFacebookAuthentication(facebookOptions);
}
您从Facebook收到的任何索赔都将传递给您的自定义用户服务的AuthenticateExternal
方法。在这一点上,他们是你的主张做任何你想做的事。
如果你没有从Facebook得到你想要的声明,我建议你先建立一个独立的MVC应用程序来解决这个问题。
我刚刚使用facebook图来获取用户配置文件。
用户服务可能是另一种方式,但这对我有效
using (var client = new HttpClient())
{
var result = client.GetAsync("https://graph.facebook.com/me?fields=first_name,last_name&access_token=" + context.AccessToken).Result;
if (result.IsSuccessStatusCode)
{
var userInformation = result.Content.ReadAsStringAsync().Result;
var fbUser = JsonConvert.DeserializeObject<FacebookUser>(userInformation);
context.Identity.AddClaim(new System.Security.Claims.Claim(IdentityServer3.Core.Constants.ClaimTypes.GivenName, fbUser.first_name));
context.Identity.AddClaim(new System.Security.Claims.Claim(IdentityServer3.Core.Constants.ClaimTypes.FamilyName, fbUser.last_name));
context.Identity.AddClaim(new System.Security.Claims.Claim("role", "Guest"));
}
}
除非按照以下修改您的提供商,否则您将无法从FB获得访问令牌
OnAuthenticated = context =>
{
context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
return Task.FromResult(true);
}
获得令牌后,使用令牌调用fb并获得given_name