Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Facebook first and last name values using ASP.NET MVC 5 and OWIN?

I know that a 'Name' field is provided, but I would prefer to access the first and last names explicitly. Can someone help with this? I'm still wrapping my head around ASP.Net MVC.

like image 604
David Poxon Avatar asked Jan 05 '14 01:01

David Poxon


4 Answers

In your Startup.Auth.cs ConfigureAuth(IAppBuilder app) method, set the following for Facebook:

var x = new FacebookAuthenticationOptions();
        x.Scope.Add("email");
        x.AppId = "*";
        x.AppSecret = "**";
        x.Provider = new FacebookAuthenticationProvider()
        {
            OnAuthenticated = async context =>
                {
                    context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                    foreach (var claim in context.User)
                    {
                        var claimType = string.Format("urn:facebook:{0}", claim.Key);
                        string claimValue = claim.Value.ToString();
                        if (!context.Identity.HasClaim(claimType, claimValue))
                            context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));

                    }

                }
        };

        x.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;
        app.UseFacebookAuthentication(x);
        /*
        app.UseFacebookAuthentication(
           appId: "*",
           appSecret: "*");
         * */

Then use this to access the user's login info:

var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

And then the following to get the first name:

var firstNameClaim = loginInfo.ExternalIdentity.Claims.First(c => c.Type == "urn:facebook:first_name");
like image 75
David Poxon Avatar answered Nov 20 '22 23:11

David Poxon


Facebook changed its permission api. You can get more information about it here: https://developers.facebook.com/docs/facebook-login/permissions

Name need public_profile permission

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

And you can get it using:

var loginInfo = await authenticationManager.GetExternalLoginInfoAsync();
loginInfo.ExternalIdentity.Claims.First(c => c.Type == "urn:facebook:name")

authenticationManager is an instance, you can get using:

HttpContext.GetOwinContext().Authentication;
like image 38
Rafał Straszewski Avatar answered Nov 20 '22 21:11

Rafał Straszewski


Unfortunately this method doesn't work anymore since Facebook changed their default return values with API update 2.4

It looks like the only way to get the first_name etc. now is to use the Facebook Graph API (like this posts suggests).

I also found this post on the Katana project site that addresses this issue and already submitted a pull request but it has not been merged jet.

Hopefully this safes somebody a little bit of time ;)

like image 6
Anton Avatar answered Nov 20 '22 23:11

Anton


As of 2017, this is the code that is working for me(Thanks to David Poxon's code above). Make sure you have upgraded to version 3.1.0 of Microsoft.Owin.Security.Facebook.

In the Startup.Auth.cs (or Startup.cs in some cases), place this code:

app.UseFacebookAuthentication(new FacebookAuthenticationOptions()
{
    AppId = "***",
    AppSecret = "****",
    BackchannelHttpHandler = new HttpClientHandler(),
    UserInformationEndpoint = "https://graph.facebook.com/v2.8/me?fields=id,name,email,first_name,last_name",
    Scope = { "email" },
    Provider = new FacebookAuthenticationProvider()
    {
        OnAuthenticated = async context =>
        {
            context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
            foreach (var claim in context.User)
            {
                var claimType = string.Format("urn:facebook:{0}", claim.Key);
                string claimValue = claim.Value.ToString();
                if (!context.Identity.HasClaim(claimType, claimValue))
                    context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
            }
        }
    }
});

Then in your controller's external login callback method, add this code:

var firstName = loginInfo.ExternalIdentity.Claims.First(c => c.Type == "urn:facebook:first_name").Value;

Likewise for getting last name, use the above line and replace the urn:facebook:first_name with urn:facebook:last_name

like image 5
Syed Waqas Avatar answered Nov 20 '22 23:11

Syed Waqas