Getting the email from external providers Google and Facebook during account association step in a default MVC5 app

19,803

Solution 1

PLEASE SEE UPDATES AT THE BOTTOM OF THIS POST!

The following works for me for Facebook:

StartupAuth.cs:

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

ExternalLoginCallback method:

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

And for Google:

StartupAuth.cs

app.UseGoogleAuthentication();

ExternalLoginCallback method (same as for facebook):

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

If I set a breakpoint here:

var email = emailClaim.Value;

I see the email address for both Facebook and Google in the debugger.

Update 1: The old answer had me confused so I updated it with the code I have in my own project that I just debugged and I know works.

Update 2: With the new ASP.NET Identity 2.0 RTM version you no longer need any of the code in this post. The proper way to get the email is by simply doing the following:

  1. Startup.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 });
        }
    }
    

Solution 2

You need to explicitly configure the FacebookAuthenticationOptions to get the email address from the authenticated user.

In your MVC5 project, add these lines in the Startup.Auth.cs

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

Update Reduced my sample code to the absolute minimum. Your updated code works fine by the way, I have also tried it with both Facebook and Google.

Solution 3

In ASP.NET Core Facebook authentication the Facebook middleware seems to no longer pass in the email, even if you add it to the scope. You can work around it by using Facebook's Graph Api to request the email.

You can use any Facebook Graph Api client or roll your own, and use it to invoke the Graph api as follows:

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);
        }
    };
});

You can find a more detailed example about how to use it here: http://zainrizvi.io/2016/03/24/create-site-with-facebook-login-using-asp.net-core/#getting-the-email-address-from-facebook

Share:
19,803

Related videos on Youtube

PussInBoots
Author by

PussInBoots

Fullstack. Anything web. But mostly .NET, MVC, Razor Pages, C#, HTML, CSS, JavaScript, Docker, Kubernetes, Azure etc.

Updated on September 16, 2022

Comments

  • PussInBoots
    PussInBoots over 1 year

    Apparently you can do this with the Facebook provider by adding scopes to the FacebookAuthenticationOptions object in 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);
    

    How to do the same with Google provider? There isn't a x.Scope property for the GoogleAuthenticationOptions class/object!

  • PussInBoots
    PussInBoots over 10 years
    you're declaring scope but are not using it?
  • The Muffin Man
    The Muffin Man about 10 years
    So could we register the user with that email address instead of asking them to provide a username?
  • PussInBoots
    PussInBoots about 10 years
    Yes, you can do that. I,ve done that in my own webapp. Works fine.
  • Jeremy Cook
    Jeremy Cook about 10 years
    @TheMuffinMan be aware of the providers you choose to trust. We can bet (and verify) that companies like Facebook and Google have already verified the email address in their claims, but other providers (think random OpenID provider) may or may not.
  • Dunc
    Dunc almost 10 years
    Regarding Update 2 - I still had to use the Scope.Add("email") code to get the users email address. By default, I think you only get public profile information.
  • simbolo
    simbolo almost 10 years
    What about vary the scope during runtime and not defining them at startup?
  • Marco Alves
    Marco Alves almost 10 years
    just to point out: "loginInfo" doesn't have the "Email" property in previous versions of Microsot.AspNet.Identity.Owin. You have to update it.
  • a.farkas2508
    a.farkas2508 over 9 years
    I have an Email property, but it's still null.
  • PussInBoots
    PussInBoots over 9 years
    @a.farkas2508 did you try with a clean default MVC 5 app?
  • a.farkas2508
    a.farkas2508 over 9 years
    @PussInBoots Yes, I see an email in facebook & google login, but not in twitter. Is there some security policy, that twitter won't let me see it?
  • Brian
    Brian over 8 years
    I'm using Microsoft ASP.NET and Web Tools 2015 (Beta8) and I get a null value for a user
  • PussInBoots
    PussInBoots over 8 years
    Things might have changed in asp.net 5. The answer in this post is for 4.5.
  • alexxjk
    alexxjk about 8 years
    I've tried this solution with Microsoft.AspNet.Identity.Core.2.2.1 and FB auth and email is always null.. is it still a right approach?
  • Zain Rizvi
    Zain Rizvi about 8 years
    @alexxjk I ran into the same issue. Check out my answer below for the fix or visit my blog post at zainrizvi.io/2016/03/24/…
  • Levent KAYA
    Levent KAYA almost 8 years
  • niico
    niico over 6 years
    This also seems to apply to non core MVC 5 projects (Nov 2017) - a null loginInfo object always seems to come back.