Search code examples
asp.net-mvcfacebookasp.net-mvc-5owin

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.


Solution

  • 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");