Introduction

This article explains the authentication of your MVC application with Facebook, or you can associate your application with any of the various other OAuth providers, like Google, Twitter, and Microsoft. You can also view the registered user information in your application using this article.
In that context, at first, you should be aware of the External Login Configuration in the MVC 4 application project. So let's start to create a web application based on MVC 4 with the app in the Facebook Developer.
I also assume that you have the knowledge of creating an app on Facebook. If you need any help then see Login App with Facebook & Google

Creating the MVC Application

Step 1: Open Visual Studio
Create New Project
Step 2: Create a new ASP.NET MVC 4 Application
Create New MVC Project
Step 3: Select the Internet Application and click "OK".
Internet Application
Step 4: In your Solution Explorer, open the AuthConfig.cs file.
Authentication Config
As you can see, the Facebook authentication is disabled.
Facebook Authentication
Note: To enter the Facebook app id and secret, create an app on Facebook.

Facebook App Provider

As you know that there are various authentication providers available to register the MVC application. To register the site with the Facebook provider you can simply provide localhost in the app domain and http://localhost/ in the site URL as shown below:
Facebook Developer
Now, copy the app id and app secret of your Facebook app and paste as shown below:
Enable Facebook Authentication

External Service Login

Now, you have successfully created the app. Debug your application and open the Login link from the browser.
Step 1: Click on Facebook
Step 2: If you are connecting your app for the first time then you must enter the Facebook credentials.
Facebook Credentials
Step 3: It automatically opens the user name registration page.
Facebook Regiteration
Step 4: You can see your user name on the Home Page in the next window
Home Page

User Details in Server Explorer

Step 1: Open the Server Explorer and right-click on Default Connection to open the user table.
User Table Details
Step 2: You can see the membership table for the user information.
Membership Table

Creating Model for New Registration

You saw that you do not need to retrieve extra info for the registration. We will now see in this section that we can create extra information to register for any new user. For this you need to follow the instructions given below:
Step 1: Open the AccountModel.cs file from the Model folder and add modify your code with the following code:
  1. public class RegisterExternalLoginModel
  2. {
  3. [Required]
  4. [Display(Name = "User name")]
  5. public string UserName { get; set; }
  6. public string ExternalLoginData { get; set; }
  7. [Display(Name = "Your Name")]
  8. public string Name { get; set; }
  9. [Display(Name = "Your Page Link")]
  10. public string PageLink { get; set; }
  11. }
Step 2: Now, add a new class in this AccountModel.cs file with the following code:
  1. [Table("ExternalUserDetails")]
  2. public class ExternalUser
  3. {
  4. public int ID { get; set; }
  5. public int UserID { get; set; }
  6. public string Name { get; set; }
  7. public string PageLink { get; set; }
  8. public bool? Status { get; set; }
  9. }
Step 3: Modify the UsersContext.cs class with the following code:
  1. public class UsersContext : DbContext
  2. {
  3. public UsersContext()
  4. : base("DefaultConnection")
  5. {
  6. }
  7. public DbSet<UserProfile> UserProfiles { get; set; }
  8. public DbSet<ExternalUser> ExtraUsers { get; set; }
  9. }
Step 4: Build the solution. Open the Package Manager Console.

Retrieving the Additional Details

To retrieve the additional details, we need to modify the ExternalLoginCallback and EnternalLoginConfirmation. The additional user data is passed back with the ExtraData property that exists in the AuthenticationResult object of the VerifyAuthentication method. The Facebook client contains the following values in the ExtraData:
Step 1: Open the AccountController.cs file from the Controller folder
Step 2: Modify the else block code in the ExternalLoginCallback() with the following code:
  1. else
  2. {
  3. // User is new, ask for their desired membership name
  4. string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
  5. ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
  6. ViewBag.ReturnUrl = returnUrl;
  7. return View("ExternalLoginConfirmation", new RegisterExternalLoginModel
  8. {
  9. UserName = result.UserName,
  10. ExternalLoginData = loginData,
  11. Name=result.ExtraData["name"],
  12. PageLink=result.ExtraData["link"]
  13. });
  14. }
Step 3: Modify the if block code in the ExternalLoginConfirmation() with the following code:
  1. if (user == null)
  2. {
  3. // Insert name into the profile table
  4. UserProfile NewRegistration = db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
  5. db.SaveChanges();
  6. db.ExtraUsers.Add(new ExternalUser
  7. {
  8. UserID = NewRegistration.UserId,
  9. Name = model.Name,
  10. PageLink = model.PageLink
  11. });
  12. db.SaveChanges();
  13. OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
  14. OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);
  15. return RedirectToLocal(returnUrl);
  16. }

View Editing

Step 1: Open the ExternalLoginConfirmation.cshtml file from the Views/Account folder and modify the code with the following code:
  1. <ol>
  2. <li class="name">
  3. @Html.LabelFor(m => m.UserName)
  4. @Html.TextBoxFor(m => m.UserName)
  5. @Html.ValidationMessageFor(m => m.UserName)
  6. </li>
  7. <li>
  8. @Html.LabelFor(m=>m.Name)
  9. @Html.TextBoxFor(m=>m.Name)
  10. </li>
  11. <li>
  12. @Html.LabelFor(m=>m.PageLink)
  13. @Html.TextBoxFor(m=>m.PageLink)
  14. </li>
  15. </ol>
Step 2: Now, you are ready to debug the application, but you need to delete the user from the users table to register again.
Step 3: Debug the application and click on the log-in link and Facebook link later.
Step 4: In the next window, you can see the extra details to enter.
Facebook Regiteration Details
Step 5: Notice the ExternalUserDetails table added in the DefaultConnection.
External User Details

Facebook API

Step 1: Open Manage NuGet Packages and install the Facebook API.
Facebook Api
Step 2: In the ExternalLoginCallback()
  1. if (!result.IsSuccessful)
  2. {
  3. return RedirectToAction("ExternalLoginFailure");
  4. }
Add the following code after the preceding if block.
  1. if (result.ExtraData.Keys.Contains("accesstoken"))
  2. {
  3. Session["FbToken"] = result.ExtraData["accesstoken"];
  4. }
Step 3: Modify the LogOff() method as in the following code:
  1. [HttpPost]
  2. [ValidateAntiForgeryToken]
  3. public ActionResult LogOff()
  4. {
  5. WebSecurity.Logout();
  6. Session.Remove("FbToken");
  7. return RedirectToAction("Index", "Home");
  8. }
Step 4: Modify the if block code in the ExternalLoginConfirmation() with the following code:
  1. if (user == null)
  2. {
  3. // Insert name into the profile table
  4. UserProfile NewRegistration = db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
  5. db.SaveChanges();
  6. bool FbStatus;
  7. var NewClient = new Facebook.FacebookClient(Session["FbToken"].ToString());
  8. dynamic Response = NewClient.Get("me", new { fields = "StatusVerified" });
  9. if (Response.ContainsKey("StatusVerified"))
  10. {
  11. FbStatus = Response["StatusVerified"];
  12. }
  13. else
  14. {
  15. FbStatus = false;
  16. }
  17. db.ExtraUsers.Add(new ExternalUser
  18. {
  19. UserID = NewRegistration.UserId,
  20. Name = model.Name,
  21. PageLink = model.PageLink,
  22. Status = FbStatus
  23. });
  24. db.SaveChanges();
  25. OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
  26. OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);
  27. return RedirectToLocal(returnUrl);
  28. }
Step 5: Again repeat Steps (2, 3, 4, 5) in the View Editing Section.

Summary

This article will help you to log in to the application with the external provider using localhost enabling in the site of the Facebook app. There is no need to enable the SSL and SSL URL to the application. You can also register the extra details for the new registration. Thanks for reading.