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

后端 未结 3 1173
臣服心动
臣服心动 2020-11-30 22:02

Apparently you can do this with the Facebook provider by adding scopes to the FacebookAuthenticationOptions object in Startup.Auth.cs:

http

3条回答
  •  长情又很酷
    2020-11-30 22:35

    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

提交回复
热议问题