25

显然,您可以通过将范围添加到FacebookAuthenticationOptions对象中的 Facebook 提供程序来执行此操作Startup.Auth.cs

http://blogs.msdn.com/b/webdev/archive/2013/10/16/get-more-information-from-social-providers-used-in-the-vs-2013-project-templates.aspx

List<string> scope = new List<string>() { "email" };
var x = new FacebookAuthenticationOptions();
x.Scope.Add("email");
...
app.UseFacebookAuthentication(x);

如何与 Google 提供商做同样的事情?类/对象没有x.Scope属性GoogleAuthenticationOptions

4

3 回答 3

47

请在这篇文章的底部查看更新!

以下适用于我的Facebook

StartupAuth.cs:

var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
{
    AppId = "x",
    AppSecret = "y"
};
facebookAuthenticationOptions.Scope.Add("email");
app.UseFacebookAuthentication(facebookAuthenticationOptions);

ExternalLoginCallback 方法:

var externalIdentity = HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
var emailClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email);
var email = emailClaim.Value;

对于谷歌

启动验证.cs

app.UseGoogleAuthentication();

ExternalLoginCallback 方法(与 facebook 相同):

var externalIdentity = HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
var emailClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email);
var email = emailClaim.Value;

如果我在这里设置断点:

var email = emailClaim.Value;

我在调试器中看到了 Facebook 和 Google 的电子邮件地址。

更新 1:旧的答案让我感到困惑,所以我用我自己的项目中的代码更新了它,我刚刚调试过并且我知道它可以工作。

更新 2:使用新的ASP.NET Identity 2.0 RTM版本,您不再需要本文中的任何代码。获取电子邮件的正确方法是简单地执行以下操作:

  1. 启动.Auth.cs

        app.UseFacebookAuthentication(
           appId: "x",
           appSecret: "y");
    
        app.UseGoogleAuthentication();
    
  2. AccountController.cs

    //
    // GET: /Account/ExternalLoginCallback
    [AllowAnonymous]
    public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
    {
        var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
        if (loginInfo == null)
        {
            return RedirectToAction("Login");
        }
    
        // Sign in the user with this external login provider if the user already has a login
        var result = await SignInHelper.ExternalSignIn(loginInfo, isPersistent: false);
        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToLocal(returnUrl);
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresTwoFactorAuthentication:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl });
            case SignInStatus.Failure:
            default:
                // If the user does not have an account, then prompt the user to create an account
                ViewBag.ReturnUrl = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
        }
    }
    
于 2013-12-04T15:41:37.013 回答
6

您需要显式配置 FacebookAuthenticationOptions 以从经过身份验证的用户那里获取电子邮件地址。

在您的 MVC5 项目中,将这些行添加到 Startup.Auth.cs

        var options = new FacebookAuthenticationOptions() {
            AppId = "xxxxxxxx",
            AppSecret = "xxxxxxxxx"
        };
        options.Scope.Add("email");
        app.UseFacebookAuthentication(options);

更新 将我的示例代码减少到绝对最小值。顺便说一句,您更新的代码工作正常,我也尝试过 Facebook 和 Google。

于 2014-01-07T22:02:56.343 回答
4

在 ASP.NET Core Facebook 身份验证中,Facebook 中间件似乎不再传递电子邮件,即使您将其添加到范围。您可以通过使用 Facebook 的 Graph Api 来请求电子邮件来解决此问题。

您可以使用任何 Facebook Graph Api 客户端或滚动您自己的客户端,并使用它来调用 Graph api,如下所示:

app.UseFacebookAuthentication(options =>
{
    options.AppId = Configuration["Authentication:Facebook:AppId"];
    options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];

    options.Scope.Add("public_profile");
    options.Scope.Add("email");

    options.Events = new OAuthEvents
    {
        OnCreatingTicket = context => {
            // Use the Facebook Graph Api to get the user's email address
            // and add it to the email claim

            var client = new FacebookClient(context.AccessToken);
            dynamic info = client.Get("me", new { fields = "name,id,email" });

            context.Identity.AddClaim(new Claim(ClaimTypes.Email, info.email));
            return Task.FromResult(0);
        }
    };
});

您可以在此处找到有关如何使用它的更详细示例:http: //zainrizvi.io/2016/03/24/create-site-with-facebook-login-using-asp.net-core/#getting-the - 来自 Facebook 的电子邮件地址

于 2016-03-25T04:02:55.637 回答