Retrieve User Details From Facebook In ASP.NET Core Applications

Now, in this article, we will discuss how can we retrieve logged-in user’s details, like Full name, Date of Birth, Gender, Email etc. from Facebook.

If you are trying to retrieve the Facebook User Details like Profile Picture, Email, Name, DOB and Gender, add the following lines in Configure method of the Startup class.

  1. app.UseFacebookAuthentication(new FacebookOptions() {  
  2.     AppId = "1X884XXXX138XXXX",  
  3.         AppSecret = "0XXc3645XXX1a3c2f8bXXXX86c242XX4",  
  4.         Scope = {  
  5.             "user_birthday"//Access the date and month of a person's birthday.  
  6.             "public_profile" //Provides access to a subset of items that are part of a person's public profile.  
  7.             //A person's public profile refers to the following properties on the user object by default:  
  8.         },  
  9.         Fields = {  
  10.             "birthday"//User's DOB  
  11.             "picture"//User Profile Image  
  12.             "name"//User Full Name  
  13.             "email"//User Email  
  14.             "gender"//user's Gender  
  15.         },  
  16. });  

Here, AppId and AppSecret are fed from Facebook App. If you are still confused, please refer to my previous article.

Now, the  next step is to write some lines of code in ExternalLoginCallback method of AccountController to retrieve user details from Facebook,

The overall ExternalLoginCallback method looks like the following.
  1. // GET: /Account/ExternalLoginCallback  
  2. [HttpGet]  
  3. [AllowAnonymous]  
  4. public async Task < IActionResult > ExternalLoginCallback(string returnUrl = null, string remoteError = null) {  
  5.     if (remoteError != null) {  
  6.         ModelState.AddModelError(string.Empty, $ "Error from external provider: {remoteError}");  
  7.         return View(nameof(Login));  
  8.     }  
  9.     var info = await _signInManager.GetExternalLoginInfoAsync();  
  10.     if (info == null) {  
  11.         return RedirectToAction(nameof(Login));  
  12.     }  
  13.     // Sign in the user with this external login provider if the user already has a login.  
  14.     var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);  
  15.     if (result.Succeeded) {  
  16.         _logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);  
  17.         return RedirectToLocal(returnUrl);  
  18.     }  
  19.     if (result.RequiresTwoFactor) {  
  20.         return RedirectToAction(nameof(SendCode), new {  
  21.             ReturnUrl = returnUrl  
  22.         });  
  23.     }  
  24.     if (result.IsLockedOut) {  
  25.         return View("Lockout");  
  26.     } else {  
  27.         // If the user does not have an account, then ask the user to create an account.  
  28.         ViewData["ReturnUrl"] = returnUrl;  
  29.         ViewData["LoginProvider"] = info.LoginProvider;  
  30.         var email = info.Principal.FindFirstValue(ClaimTypes.Email);  
  31.         var name = info.Principal.FindFirstValue(ClaimTypes.Name);  
  32.         var dob = info.Principal.FindFirstValue(ClaimTypes.DateOfBirth);  
  33.         var gender = info.Principal.FindFirstValue(ClaimTypes.Gender);  
  34.         var identifier = info.Principal.FindFirstValue(ClaimTypes.NameIdentifier);  
  35.         var picture = $ "https://graph.facebook.com/{identifier}/picture?type=large";  
  36.         return View("ExternalLoginConfirmation"new ExternalLoginConfirmationViewModel {  
  37.             Email = email, //User Email  
  38.                 Name = name, //user Display Name  
  39.                 DOB = dob.ToString(), //User DOB  
  40.                 Gender = gender, //User Gender  
  41.                 Picture = picture //User Profile Image  
  42.         });  
  43.     }  

Explanation

  • Get external login information for Current login. [In our case, Facebook]
    1. var info = await _signInManager.GetExternalLoginInfoAsync();  
  • Sign in the user with this external login provider if the user already has a login.
    1. // Sign in the user with this external login provider if the user already has a login.  
    2. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);  
    3. if (result.Succeeded) {  
    4.     _logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);  
    5.     return RedirectToLocal(returnUrl);  
    6. }  
  • If the user does not have an account, then ask the user to create an account.
    1. // If the user does not have an account, then ask the user to create an account.  
    2. ViewData["ReturnUrl"] = returnUrl;  
    3. ViewData["LoginProvider"] = info.LoginProvider;  
    4. var email = info.Principal.FindFirstValue(ClaimTypes.Email);  
    5. var name = info.Principal.FindFirstValue(ClaimTypes.Name);  
    6. var dob = info.Principal.FindFirstValue(ClaimTypes.DateOfBirth);  
    7. var gender = info.Principal.FindFirstValue(ClaimTypes.Gender);  
    8. var identifier = info.Principal.FindFirstValue(ClaimTypes.NameIdentifier);  
    9. var picture = $ "https://graph.facebook.com/{identifier}/picture?type=large";  
    10. return View("ExternalLoginConfirmation"new ExternalLoginConfirmationViewModel {  
    11.     Email = email, //User Email  
    12.         Name = name, //user Display Name  
    13.         DOB = dob.ToString(), //User DOB  
    14.         Gender = gender, //User Gender  
    15.         Picture = picture //User Profile Image  
    16. });  

Here, info.Principal.FindFirstValue(ClaimTypes.[Name]) is responsible to retrieve the claims associated with that account.

All the retrieved claims (Email, Name, DOB, Gender and Picture) associated with user are then passed to ExternalLoginConfirmation View page to confirm user registration .

ExternalLoginConfirmationViewModel

Modify ExternalLoginConfirmationViewModel as below:

Retrieve User Details from Facebook in ASP.NET Core Applications by Nishan Aryal

ExternalLoginConfirmation View Page

Step 1

Navigate to Views => Accounts => ExternalLoginConfirmation.cshtml.

Retrieve User Details from Facebook in ASP.NET Core Applications by Nishan Aryal

Step 2

Now, replace the design code with the following.
  1. <h2>@ViewData["Title"].</h2>  
  2. <div class="row">  
  3.     <div class="col-md-offset-3 col-md-6">  
  4.         <div class="panel panel-primary">  
  5.             <div class="panel-heading"> <b>Associate details from @ViewData["LoginProvider"] account.</b> </div>  
  6.             <div class="panel-body">  
  7.                 <div class="row">  
  8.                     <div class="col-md-4"> <img src="@Model.Picture" title="@Model.Name" alt="@Model.Name" class="img-rounded img-thumbnail" style="height:160px;" /> </div>  
  9.                     <div class="col-md-8">  
  10.                         <p class="text-info"> You've successfully authenticated with <strong>@ViewData["LoginProvider"]</strong>. Please modify your details and click <strong>Register Now</strong> to complete your registration. </p> <strong>Name :</strong><span> @Model.Name</span> <br /> <strong>DOB :</strong><span> @String.Format("{0:dddd, MMMM d, yyyy}", Convert.ToDateTime(Model.DOB))</span> <br /> <strong>Gender :</strong><span> @Model.Gender.ToString()</span> <br /> <strong>Email :</strong><span> @Model.Email</span> </div>  
  11.                 </div>  
  12.                 <div class="row">  
  13.                     <form asp-controller="Account" asp-action="ExternalLoginConfirmation" asp-route-returnurl="@ViewData[" ReturnUrl "]" method="post" class="form-horizontal">  
  14.                         <center>  
  15.                             <hr />  
  16.                             <div asp-validation-summary="All" class="text-danger"></div>  
  17.                             <div class="form-group"> <label asp-for="Email" class="col-md-2 control-label"></label>  
  18.                                 <div class="col-md-10"> <input asp-for="Email" class="form-control" autofocus /> <span asp-validation-for="Email" class="text-danger"></span> </div>  
  19.                             </div>  
  20.                             <div class="form-group">  
  21.                                 <div class="col-md-offset-2 col-md-10"> <button type="submit" class="btn btn-success"><i class="glyphicon glyphicon-registration-mark"></i> Register Now</button> </div>  
  22.                             </div>  
  23.                         </center>  
  24.                     </form>  
  25.                 </div>  
  26.             </div>  
  27.         </div>  
  28.     </div>  
  29. </div> @section Scripts { @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } }  

Application Execution

Now, rebuild and Run (Ctrl + F5) the application.

Navigate to the Login Page and login using Facebook credentials.

Once the login is successful with Facebook, you will be redirected to ExternalLoginConfirmation page which will display your Facebook details just like below.

Retrieve Details from Facebook in ASP.NET Core Application

You can "Register Now" into your Web App.

Summary

So far, we have learned how to

In next article, we will learn how to add custom properties in ASP.NET Identity, migrate those properties as Columns, and save the data retrieved from Facebook in Database. By default, ASP.NET Core application doesn’t save Name, DOB, Gender and Profile Picture of users retrieved from External Login Providers.