How to get values โ€‹โ€‹for the first and last Facebook name using ASP.NET MVC 5 and OWIN?

I know that the "Name" field is provided, but I would prefer to explicitly access the first and last name. Can anyone help with this? I am still hugging ASP.Net MVC.

+19
facebook asp.net-mvc asp.net-mvc-5 owin
Jan 05 '14 at 1:26
source share
7 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 login information:

 var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); 

And then the following to get the name:

 var firstNameClaim = loginInfo.ExternalIdentity.Claims.First(c => c.Type == "urn:facebook:first_name"); 
+43
Jan 05 '14 at 2:16
source share

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

Public_profile permission is required for the name.

 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 use:

 HttpContext.GetOwinContext().Authentication; 
+7
May 14 '15 at 18:52
source share

Unfortunately, this method no longer works, as Facebook has changed the default return values โ€‹โ€‹with API 2.4 update

It seems like the only way to get first_name, etc. now use the Facebook Graph API ( as the messages say ).

I also found this post on the Katana project website, which solves this problem and has already submitted a transfer request, but it has not been merged.

Hope this saves a little time;)

+6
02 Sep '15 at 10:02
source share

Since 2017, this is the code that works for me (thanks to David Poxon's code above). Make sure you update version 3.1.0 from Microsoft.Owin.Security.Facebook .

In Startup.Auth.cs (or Startup.cs in some cases) put 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 external controller callback method add this code:

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

Similarly, to get the last name, use the line above and replace urn:facebook:first_name with urn:facebook:last_name

+1
Jul 25 '17 at 6:19 06:19
source share
  private Uri RedirectUri { get { var uriBuilder = new UriBuilder(Request.Url); uriBuilder.Query = null; uriBuilder.Fragment = null; uriBuilder.Path = Url.Action("FacebookCallback"); return uriBuilder.Uri; } } [AllowAnonymous] public ActionResult Facebook() { var fb = new FacebookClient(); var loginUrl = fb.GetLoginUrl(new { client_id = "296002327404***", client_secret = "4614cd636ed2029436f75c77961a8***", redirect_uri = RedirectUri.AbsoluteUri, response_type = "code", scope = "email" // Add other permissions as needed }); return Redirect(loginUrl.AbsoluteUri); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult LogOff() { FormsAuthentication.SignOut(); return View("Login"); } public ActionResult FacebookCallback(string code) { var fb = new FacebookClient(); dynamic result = fb.Post("oauth/access_token", new { client_id = "296002327404***", client_secret = "4614cd636ed2029436f75c77961a8***", redirect_uri = RedirectUri.AbsoluteUri, code = code }); var accessToken = result.access_token; // Store the access token in the session for farther use Session["AccessToken"] = accessToken; // update the facebook client with the access token so // we can make requests on behalf of the user fb.AccessToken = accessToken; // Get the user information dynamic me = fb.Get("me?fields=first_name,middle_name,last_name,id,email"); string email = me.email; string firstname = me.first_name; string middlename = me.middle_name; string lastname = me.last_name; db.Insert_customer(firstname,email,null,null,null,null,null,null,null,null,null,null,1,1,System.DateTime.Now,1,System.DateTime.Now); // Set the auth cookie FormsAuthentication.SetAuthCookie(email, false); return RedirectToAction("Index", "Home"); } } } 
0
Jun 07 '16 at 12:33
source share

Facebook has changed the way the Graph API returns a value in Update 2.4 . Now you need to explicitly specify all the fields that you want to return.

See this note: facebook for developers Information update :

Graphical API changes in version 2.4

In the past, responses from Graph API calls returned a set of fields by default. To reduce the payload size and improve latency on mobile devices on networks, we have reduced the number of default fields returned for most Graph API calls. In version 2.4, you need to declaratively list the response fields for your calls.

To get Email, FirstName and LastName from facebook:

First you need to install the Facebook SDK for .NET nuget package

Then in your startup.Auth.cs change your Facebook authentication configuration as follows:

  app.UseFacebookAuthentication(new FacebookAuthenticationOptions { // put your AppId and AppSecret here. I am reading them from AppSettings AppId = ConfigurationManager.AppSettings["FacebookAppId"], AppSecret = ConfigurationManager.AppSettings["FacebookAppSecret"], Scope = { "email" }, Provider = new FacebookAuthenticationProvider { OnAuthenticated = context => { context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken)); return Task.FromResult(true); } } }); // this is no longer needed //app.UseFacebookAuthentication( // appId: ConfigurationManager.AppSettings["FacebookAppId"], // appSecret: ConfigurationManager.AppSettings["FacebookAppSecret"]); 

Finally, in your AccountController add the following code: ExternalLoginCallback method:

 if (string.Equals(loginInfo.Login.LoginProvider, "facebook", StringComparison.CurrentCultureIgnoreCase)) { var identity = AuthenticationManager.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie); var access_token = identity.FindFirstValue("FacebookAccessToken"); var fb = new FacebookClient(access_token); // you need to specify all the fields that you want to get back dynamic myInfo = fb.Get("/me?fields=email,first_name,last_name"); string email = myInfo.email; string firstName = myInfo.first_name; string lastName = myInfo.last_name; } 

Refer to facebook API Guid for more options that you can return.

0
Nov 16 '17 at 6:07
source share

Add first and last name to facebook scope option

 var facebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions() { AppId = "your app id", AppSecret = "your app secret", }; facebookOptions.Scope.Add("email"); facebookOptions.Scope.Add("first_name"); facebookOptions.Scope.Add("last_name"); return facebookOptions; 
-3
Sep 09 '14 at 8:29
source share



All Articles