Introduction To Facebook OAuth Provider in MVC 4

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:
  • Open the Package Manager Console in the Library Package.
  • Execute the command: enable-migrations
  • Execute the command: add-migration initial-IgnoreChanges
  • Execute the command: update-database
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 { getset; }  
  6.    
  7.     public string ExternalLoginData { getset; }  
  8.    
  9.     [Display(Name = "Your Name")]  
  10.     public string Name { getset; }  
  11.    
  12.     [Display(Name = "Your Page Link")]  
  13.     public string PageLink { getset; }  

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 { getset; }  
  5.     public int UserID { getset; }  
  6.     public string Name { getset; }  
  7.     public string PageLink { getset; }  
  8.     public bool? Status { getset; }  

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.    
  8.     public DbSet<UserProfile> UserProfiles { getset; }  
  9.     public DbSet<ExternalUser> ExtraUsers { getset; }  

Step 4: Build the solution. Open the Package Manager Console.
  • Execute the command: add-migration AddExternalUserDetails
  • Execute the command: update-database

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:
  • id
  • name
  • link
  • gender
  • accesstoken
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.    
  8.     return View("ExternalLoginConfirmation"new RegisterExternalLoginModel  
  9.     {  
  10.         UserName = result.UserName,  
  11.         ExternalLoginData = loginData,  
  12.         Name=result.ExtraData["name"],  
  13.         PageLink=result.ExtraData["link"]  
  14.    
  15.     });  

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.    
  7.     db.ExtraUsers.Add(new ExternalUser  
  8.     {  
  9.         UserID = NewRegistration.UserId,  
  10.         Name = model.Name,  
  11.         PageLink = model.PageLink  
  12.     });  
  13.    
  14.     db.SaveChanges();  
  15.    
  16.     OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);  
  17.     OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);  
  18.    
  19.     return RedirectToLocal(returnUrl);  

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

Add the following code after the preceding if block.
  1. if (result.ExtraData.Keys.Contains("accesstoken"))  
  2. {  
  3.     Session["FbToken"] = result.ExtraData["accesstoken"];  

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.    
  8.     return RedirectToAction("Index""Home");  

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.    
  7.     bool FbStatus;  
  8.    
  9.     var NewClient = new Facebook.FacebookClient(Session["FbToken"].ToString());  
  10.                         dynamic Response = NewClient.Get("me"new { fields = "StatusVerified" });  
  11.     if (Response.ContainsKey("StatusVerified"))  
  12.     {  
  13.         FbStatus = Response["StatusVerified"];  
  14.     }  
  15.     else  
  16.     {  
  17.         FbStatus = false;  
  18.     }  
  19.    
  20.     db.ExtraUsers.Add(new ExternalUser  
  21.     {  
  22.         UserID = NewRegistration.UserId,  
  23.         Name = model.Name,  
  24.         PageLink = model.PageLink,  
  25.         Status = FbStatus  
  26.     });  
  27.    
  28.     db.SaveChanges();  
  29.    
  30.     OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);  
  31.     OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);  
  32.    
  33.     return RedirectToLocal(returnUrl);  

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.


Similar Articles