我有一个.net核心2.0应用程序,我正在实施谷歌,推特和脸书等外部登录提供商。我需要获取用户的显示名称和个人资料图片,并且无法在.net core 2.0中找到如何实现此目的的任何文档。
我添加了这样的身份验证:https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/
以下是我的Twitter登录和回调函数......
node()[@key = 'value']
看起来您可以从info.Principal.Claims获取一些项目,但是没有任何内容可以显示用户的显示名称或个人资料图片。
如何获取各种登录提供商的显示名称或个人资料图片?
答案 0 :(得分:2)
我终于想通了......你需要在配置身份验证时添加声明。这些声明会查看生成的json响应并从中提取项目。相关的行是ClaimActions项目。
services.AddAuthentication()
.AddTwitter(twitterOptions =>
{
twitterOptions.ConsumerKey = cfg.SystemConfig["TwitterConsumerKey"];
twitterOptions.ConsumerSecret = cfg.SystemConfig["TwitterConsumerSecret"];
twitterOptions.SaveTokens = true;
twitterOptions.RetrieveUserDetails = true;
twitterOptions.ClaimActions.MapJsonKey("display-name", "name");
twitterOptions.ClaimActions.MapJsonKey("profile-image-url", "profile_image_url_https");
})
.AddFacebook(facebookOptions =>
{
facebookOptions.AppId = cfg.SystemConfig["FacebookClientId"];
facebookOptions.AppSecret = cfg.SystemConfig["FacebookClientSecret"];
facebookOptions.SaveTokens = true;
facebookOptions.ClaimActions.MapJsonKey("display-name", "name");
})
.AddGoogle(googleOptions =>
{
googleOptions.ClientId = cfg.SystemConfig["GoogleClientId"];
googleOptions.ClientSecret = cfg.SystemConfig["GoogleClientSecret"];
googleOptions.SaveTokens = true;
googleOptions.ClaimActions.MapJsonSubKey("profile-image-url", "image", "url");
googleOptions.ClaimActions.MapJsonKey("display-name", "displayName" );
});
使用
获取回调中的登录信息后var info = await SignInManager.GetExternalLoginInfoAsync();
如果成功填充,您可以查询声明并找到值
var profileImageClaim = info.Principal.Claims.Where(x => x.Type == "profile-image-url").FirstOrDefault();
Facebook图片与谷歌和推特不同,可以使用...
找到var claim = info.Principal.Claims.Where(x => x.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").FirstOrDefault();
var url = "http://graph.facebook.com/" + claim.Value + "/picture";
答案 1 :(得分:0)
在ASP.NET Core 2.0中,FacebookOptions使用ClaimActions上的扩展方法来映射UserInformationEndpoint返回的配置文件数据。
ClaimActions.MapJsonKey(ClaimTypes.DateOfBirth, "birthday");
在上面的映射中,"生日"是Facebook Graph API响应中的顶级属性,该属性已映射到声明ClaimTypes.DateOfBirth
所代表的值。
要获取个人资料图片,您可以执行相同的操作,但由于图谱API响应中的图片是嵌套的JSON对象,因此您必须使用MapCustomJson()
services.AddAuthentication()
.AddFacebook(options =>
{
// ...other options omitted
options.Fields.Add("picture");
options.ClaimActions.MapCustomJson("urn:facebook:picture",
claim => (string)claim.SelectToken("picture.data.url"));
})
此处,claim
是NewtonSoft JObject
,它使用JPath
语法选择嵌套属性值并将其强制转换为字符串。
个人资料图片网址现在会显示在您的Claims
列表中。