加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 访问OAuth中的电子邮件地址ExternalLoginCallbac

发布时间:2020-12-16 00:24:29 所属栏目:asp.Net 来源:网络整理
导读:参见英文答案 Why new fb api 2.4 returns null email on MVC 5 with Identity and oauth 2?5个答案使用Facebook API v2.3,如果设置了以下设置,用户的电子邮件地址将返回到ExternalLoginCallback; app.UseFacebookAuthentication(new FacebookAuthenticati
参见英文答案 > Why new fb api 2.4 returns null email on MVC 5 with Identity and oauth 2?5个答案使用Facebook API v2.3,如果设置了以下设置,用户的电子邮件地址将返回到ExternalLoginCallback;
app.UseFacebookAuthentication(new FacebookAuthenticationOptions
{
    AppId = "XXX",AppSecret = "XXX",Scope = { "email" }
});

但是,任何只能针对v2.4(7月8日发布)的应用程序不再将电子邮件地址返回到ExternalLoginCallback。

我认为这可能与here所列的v2.4变更有关;

Declarative Fields

To try to improve performance on mobile networks,
Nodes and Edges in v2.4 requires that you explicitly request the
field(s) you need for your GET requests. For example,GET
/v2.4/me/feed
no longer includes likes and comments by default,but
GET /v2.4/me/feed?fields=comments,likes will return the data. For more
details see the docs on how to request specific fields.

如何才能立即访问此电子邮件地址?

解决方法

要解决这个问题,我不得不从nuget安装 Facebook SDK for .NET,并分别查询电子邮件地址。

在ExternalLoginCallback方法中,我添加了一个条件来填充Facebook Graph API中的电子邮件地址;

var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

if (loginInfo == null)
{
    return RedirectToAction("Login");
}

// added the following lines
if (loginInfo.Login.LoginProvider == "Facebook")
{
    var identity = AuthenticationManager.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie);
    var access_token = identity.FindFirstValue("FacebookAccessToken");
    var fb = new FacebookClient(access_token);
    dynamic myInfo = fb.Get("/me?fields=email"); // specify the email field
    loginInfo.Email = myInfo.email;
}

并获得FacebookAccessToken我扩展了ConfigureAuth;

app.UseFacebookAuthentication(new FacebookAuthenticationOptions
{
    AppId = "XXX",Scope = { "email" },Provider = new FacebookAuthenticationProvider
    {
        OnAuthenticated = context =>
        {
            context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken",context.AccessToken));
            return Task.FromResult(true);
        }
    }
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读