如何在 MVC 中的 OAuth 期间获取 Facebook/Google/Twitter 详细信息?



我意识到这个问题在过去的10年里被问了很多,回答了很多,但我需要一个比我能找到的大多数人更现代的答案。

我有一个 ASP.Net 的MVC项目(C#(,并遵循MS指南启用Facebook和Google+身份验证。这非常简单,在提供程序中注册应用程序并在startup.auth中取消注释三行.cs - 超级,超级简单。它也"只是工作",bango 我在数据库中创建了可以通过这些提供程序登录的新用户。温德巴。

像许多应用程序一样,虽然我需要的不仅仅是身份验证,但我还需要少量的身份 - 名字、姓氏、电子邮件、生日、个人资料图像(如果可用(。

使用FacebookAuthenticationOptions中的范围和字段的组合,我设法获得了Facebook授权屏幕,以警告用户该应用程序想要他们的生日,但是尽我所能,我找不到在OAuth进程中返回此信息的任何地方或任何可能代表我要求的其他六个字段的声明。

许多在线"解决方案"都谈到了覆盖FacebookAuthenticationOptions.Provider(FacebookAuthenticationProvider(的"OnAuthenticated"委托。我已经粘贴了一些被盗的代码,但它从未到达那里的断点。

在我与Facebook合作之后,我希望与Google+,Twitter和Microsoft帐户提供商重复此操作,我希望这是一种标准化的方法,我可以告诉每个提供商我想要哪些字段的格式,然后使用标准getter将它们全部删除在某个地方。据我了解,这实际上是OAuth的全部基本点-不是吗?

所以在我的startup.auth中.cs(当然是假ID和秘密(:

app.UseFacebookAuthentication(new FacebookAuthenticationOptions
{
AppId = "xxxxxxxxxxx",
AppSecret = "xxxxxxxxxxxxxxxxxxxxx",
Scope = { "user_birthday", "public_profile", "email" },
Fields = { "user_birthday", "picture", "name", "email", "gender", "first_name", "last_name" },
Provider = new FacebookAuthenticationProvider
{ 
OnAuthenticated = async ctx =>
{
Console.WriteLine("auth"); //this breakpoint never hits
ctx.Identity.AddClaim(new Claim("FacebookAccessToken", ctx.AccessToken));
foreach (var claim in ctx.User)
{
var claimType = string.Format("urn:facebook:{0}", claim.Key);
string claimValue = claim.Value.ToString();
if (!ctx.Identity.HasClaim(claimType, claimValue))
{
ctx.Identity.AddClaim(new Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
}
}
}
}
});

感谢@Jeremy Thompson在评论中指出我最初认为只是我最初偷的同一件事的另一个副本,但实际上触发了我自己以某种方式解决这个问题。

Jeremy 链接到"有效"的解决方案,它看起来很像我的原始代码,除了 OnAuthenticated 方法正在触发。不幸的是,它实际上没有生日,所以我添加了它,然后它停止工作。啊哈。。。

因此,瞪大了我是如何到达那里的,问题似乎是发生了一个静默异常,该异常阻止了此OnAuthentication触发,就我而言,这是因为我的字段名称不正确。这是返回我的姓名,电子邮件,生日,当前城镇和个人资料图片的工作代码(在您自己的系统中创建个人资料所需的基本要素!

当然,在OWIN启动类中:

app.UseFacebookAuthentication(new FacebookAuthenticationOptions
{
AppId = "...", //Your App Id of course
AppSecret = "...", //Your App Secret of course
Scope = { "user_birthday", "public_profile", "email", "user_gender", "user_location" },
Fields = { "birthday", "picture", "name", "email", "gender", "first_name", "last_name", "location" }, //notice the fields are not prefixed with "user_". This was 
Provider = new FacebookAuthenticationProvider
{
OnAuthenticated = async ctx =>
{
ctx.Identity.AddClaim(new Claim("FacebookAccessToken", ctx.AccessToken));
foreach (var claim in ctx.User)
{
var claimType = string.Format("urn:facebook:{0}", claim.Key);
string claimValue = claim.Value.ToString();
if (!ctx.Identity.HasClaim(claimType, claimValue))
{
ctx.Identity.AddClaim(new Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
}
}
}
}
});

现在,在我的AccountController的ExternalLoginCallback函数中,我可以通过查看loginInfo.Claims属性(loginInfo如下(来访问一堆属性。

var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

相关内容

最新更新