简体   繁体   中英

Get user email from facebook in asp net

I'm trying to get user name and user email from facebook. I read a lot of information on this topic and this is my final code that works for some reason only on my facebook app admin account:

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {

        /*Other external login options*/

         var FacebookOptions = new FacebookAuthenticationOptions()
                {
                    AppId = "My App Id",
                    AppSecret = "My App Secret",
                    SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                    BackchannelHttpHandler = new FacebookBackChannelHandler(),
                    UserInformationEndpoint = "https://graph.facebook.com/v2.7/me?fields=id,name,email"
                };


    }
}
public class FacebookBackChannelHandler : HttpClientHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        if (!request.RequestUri.AbsolutePath.Contains("/oauth"))
        {
            request.RequestUri = new Uri(request.RequestUri.AbsoluteUri.Replace("?access_token", "&access_token"));
        }

        return await base.SendAsync(request, cancellationToken);
    }
}
public class AccountController : Controller
{
    public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
    {
        var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
        /*my sign in code that works on my facebook app admin account*/
    }  
}    

On every over account I get loginInfo.Email is equal to null .

In developers.facebook.com I have:

批准的项目

When someone clicks on "Login with Facebook" he gets this message:

第一个Facebook登录页面

If I click "Review the info you provide" i get:

查看您提供的信息

What am I missing? Why doesn't it work?

Finally found an answer! All that needs to be done is to add Scope = { "email" } to FacebookOptions and that's solves the problem!

My code now:

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {

        /*Other external login options*/

         var FacebookOptions = new FacebookAuthenticationOptions()
                {
                    AppId = "My App Id",
                    AppSecret = "My App Secret",
                    SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                    BackchannelHttpHandler = new FacebookBackChannelHandler(),
                    Scope = { "email" },
                    UserInformationEndpoint = "https://graph.facebook.com/v2.7/me?fields=id,name,email"
                };
    }
}

The rest of the code stays the same. I only added error page for the case if this problem returns:

public class AccountController : Controller
{
    public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
    {
        var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
        if(loginInfo.Email == null)
        {
             return RedirectToAction("FacebookError", "Account");
        }
        /*my sign in code*/
    }  
}   

Facebook offers people full control over the permissions they grant to an app. That control extends beyond the point at which they see the login dialog. They can choose not to grant certain permissions during the login process. They can also revoke permissions in their Facebook privacy settings at any time. Apps should check for the validity of permissions before attempting to perform an API call where they are required. For example, checking that email action is still granted before attempting to publish an Open Graph story. facebook provides the a graph API endpoint to retrieve a list of granted permissions:

GET /{user-id}/permissions

The call must be made with either a user access token or your app access token. The call will return a JSON string containing the permission names which have been granted to the app and their status:

{
  "data": [
    {
      "permission": "public_profile",
      "status": "granted"
    },
    {
      "permission": "publish_actions",
      "status": "granted"
    },
    {
      "permission": "user_friends",
      "status": "declined"
    }
  ]
}

by using this, you can detect whether it is possible or not to fetch the information you want. hope this helps.

reference: https://developers.facebook.com/docs/facebook-login/permissions/requesting-and-revoking

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM