简体   繁体   中英

Asp.net identity get facebook information

I have searched online on the following code for getting code information, but I have some questions

1) facebook.Options.Scope.Add("email") : How to determine what to put in email? For example what should I put if I need name or first name?

2) ext.Claims.First(x => x.Type.Contains("email")).Value; How do I determine the email here? Let's say I want first name, how do I know the first name is first_name of first-name of firstname

 var facebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions()
            {
                AppId = "AppId",
                AppSecret = "AppSecret"
            };
            facebookOptions.Scope.Add("email");
            app.UseFacebookAuthentication(facebookOptions);

 ClaimsIdentity ext = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
            var email = ext.Claims.First(x => x.Type.Contains("email")).Value;

You can't directly get all of Facebook profile information from claims added through facebookOptions scope. You have to add scopes like below and use FacebookClient as explain.

var facebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions()
            {
                AppId = "AppId",
                AppSecret = "AppSecret"
            };
            facebookOptions.Scope.Add("email");            
            facebookOptions.Scope.Add("public_profile");
            app.UseFacebookAuthentication(facebookOptions);

Then you can get Facebook user information using FacebookClient.

[Authorize]
public async Task<ActionResult> FacebookInfo()
{
    var claimsforUser = await UserManager.GetClaimsAsync(User.Identity.GetUserId());
    var access_token = claimsforUser.FirstOrDefault(x => x.Type == "FacebookAccessToken").Value;
    var fb = new FacebookClient(access_token);
    dynamic myInfo = fb.Get("/me"); **// Check this with Facebook api to get profile information.**

} 

Note that: If you only need to get Facebook user full name, then check your claims, you'll see user's full name is there.

More information

Hope this helps,

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