Social Provider Access in Web Application With MVC 5

Introduction

This article explains how to access the social providers in a MVC based ASP.NET Web Application. Facebook is used for the example of a social provider. There are various types of social providers available to be accessed, such as Google, Twitter and Microsoft. You can access your information in your social account such as you can access your friend's photos in your Facebook account.

In that context, I am creating a MVC based ASP.NET Web Application and I am also assuming that you have the knowledge necessary to configure the social login provider in your Web Application. You can visit Configure the External Login Options in MVC as a reference to access the external authentication for your ASP.NET Web Application.

Prerequisites

The following are the prerequisites:

  • Create an ASP.NET MVC Web Application in Visual Studio 2013.
  • Enable the Facebook Provider

Now let's follow the sections mentioned below to proceed:

  • Facebook Authentication
  • Controller and Model Editing
  • Adding View
  • Access Application

Facebook Authentication

To authenticate the Facebook provider, use the following procedure.

Step 1: In your Solution Explorer, open the Startup authentication file as shown below:

Startup Authentication File

Step 2: Find the ConfigureAuth() method and modify your code with the following code:

  1. //app.UseTwitterAuthentication(    
  2.    //   consumerKey: "",    
  3.    //   consumerSecret: "");    
  4.      
  5.    List<string> Social = new List<string>() { "email""friends_about_me""friends_photos" };    
  6.      
  7.    var FbFriends = new FacebookAuthenticationOptions();    
  8.      
  9.    FbFriends.Scope.Add("email");    
  10.    FbFriends.Scope.Add("friends_about_me");    
  11.    FbFriends.Scope.Add("friends_photos");    
  12.    FbFriends.AppId = "App ID Value";    
  13.    FbFriends.AppSecret="App Secret Value";    
  14.      
  15.    FbFriends.Provider=new FacebookAuthenticationProvider()    
  16.    {    
  17.        OnAuthenticated = async FbContext =>    
  18.            {    
  19.      
  20.                FbContext.Identity.AddClaim(    
  21.                new System.Security.Claims.Claim("FacebookAccessToken", FbContext.AccessToken));    
  22.                     }    
  23.     };           FbFriends.SignInAsAuthenticationType=DefaultAuthenticationTypes.ExternalCookie;    
  24.   app.UseFacebookAuthentication(FbFriends);       
  25. //app.UseGoogleAuthentication(); 

In the code above, FacebookAuthenticationProvider() is called each time the user authenticates with Facebook and the data is to be stored in the FbContext.FacebookAccessToken to access the friends of the user.

Controller and Model Editing

Now we need to edit our Controller and Model to access the information of User Facebook Account. Use the following procedure to do that.

Step 1: At first open your Login file to create an Action.

Shared Files in MVC

Step 2: Modify your code with the following code:

  1. <ul class="nav navbar-nav navbar-right">    
  2.   <li>    
  3.       @Html.ActionLink("Hello " + User.Identity.GetUserName() + "!""Manage""Account", routeValues: null, htmlAttributes: new { title = "Manage" })    
  4.   </li>    
  5.      
  6.   <li>    
  7.       @Html.ActionLink("Facebook Friends""FacebookFriends""Account")    
  8.   </li>    
  9.      
  10.   <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>    
  11. </ul>

Step 3: Now open the AccountController.cs file from the Solution Explorer and proceed with the following sections to edit the controller:

  • Adding Task

    Add the following Task in your Account Controller:
    1. private async Task FbAuthenticationToken(ApplicationUser User)    
    2. {    
    3.     var claims = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);    
    4.     if (claims != null)    
    5.     {    
    6.         var getclaim = await UserManager.GetClaimsAsync(User.Id);    
    7.         var FbToken = claims.FindAll("FacebookAccessToken").First();    
    8.         if (getclaim.Count() <= 0)    
    9.         {    
    10.             await UserManager.AddClaimAsync(User.Id, FbToken);    
    11.         }    
    12.     }    
    13. }     
  • Modify the ExternalLoginCallback()

    Modify the external login provider in this method with the following code:

    1. // Sign in the user with this external login provider if the user already has a login    
    2.     
    3. var user = await UserManager.FindAsync(loginInfo.Login);    
    4. if (user != null)    
    5. {    
    6.     await FbAuthenticationToken(user);    
    7.     await SignInAsync(user, isPersistent: false);    
    8.     return RedirectToLocal(returnUrl);    
    9. }  

     

  • Modify the LinkLoginCallback()

    Modify this method with this code: 

    1. // GET: /Account/LinkLoginCallback    
    2. publicasyncTask<ActionResult> LinkLoginCallback()    
    3. {    
    4.     var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId());    
    5.             if (loginInfo == null)    
    6.             {    
    7.                 return RedirectToAction("Manage",new { Message = ManageMessageId.Error });    
    8.             }    
    9.             var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login);    
    10.     if (result.Succeeded)    
    11.     {    
    12.         var FbUser = await UserManager.FindByIdAsync(User.Identity.GetUserId());    
    13.         await FbAuthenticationToken(FbUser);    
    14.         return RedirectToAction("Manage");    
    15.     }    
    16.     return RedirectToAction("Manage",new { Message = ManageMessageId.Error });    
    17. }  

     

  • Modify the ExternalLoginConfirmation()

    Modify the external login provider in this method with the following code:

    1. // Get the information about the user from the external login provider    
    2.     
    3. var info = await AuthenticationManager.GetExternalLoginInfoAsync();    
    4. if (info == null)    
    5. {    
    6.     return View("ExternalLoginFailure");    
    7. }    
    8. var user = newApplicationUser() { UserName = model.UserName };    
    9. var result = await UserManager.CreateAsync(user);    
    10. if (result.Succeeded)    
    11. {    
    12.     result = await UserManager.AddLoginAsync(user.Id, info.Login);    
    13.     if (result.Succeeded)    
    14.     {    
    15.         await FbAuthenticationToken(user);    
    16.         await SignInAsync(user, isPersistent: false);    
    17.         return RedirectToLocal(returnUrl);    
    18.     }    
    19. }    
    20. AddErrors(result);     

     

  • Facebook Package

    Install the Facebook NuGet Package in your application.

  • Modify the AccountViewModel

    Add the following code in your AccountViewModel.cs file in the Account Folder:

    1. public class FacebookViewModel
    2. {    
    3.     [Required]    
    4.     [Display(Name = "Friend's name")]    
    5.      
    6.     public string Name { get;set; }    
    7.      
    8.     public string Image { get;set; }    
    9. }  

     

  • Modify Controller

    Add the following code in the Account Controller to access the Facebook Friends Information:

    1. public async Task<ActionResult> FacebookFriends()    
    2. {    
    3.     var UserClaim = await    
    4.      
    5.         UserManager.GetClaimsAsync(User.Identity.GetUserId());    
    6.      
    7.     var token = UserClaim.FirstOrDefault(fb => fb.Type == "FacebookAccessToken").Value;    
    8.      
    9.     var FbClient = newFacebookClient(token);    
    10.      
    11.     dynamic FacebookFriends = FbClient.Get("/me/friends");    
    12.     var FbFriends=newList<FacebookViewModel>();    
    13.     foreach (dynamic MyFriend in FacebookFriends.data)    
    14.     {    
    15.         FbFriends.Add(newFacebookViewModel()    
    16.         {    
    17.             Name=MyFriend.name,    
    18.             Image= @"https://graph.facebook.com/" + MyFriend.id + "/picture?type=large"    
    19.         });    
    20.     }    
    21.      
    22.     return View(FbFriends);    
    23. }   

     

Adding View

The final step is to add the View to access Facebook. So, proceed with the following procedure.

Step 1: Add a View to your Account Folder:

Adding View in MVC

Step 2: In the wizard, enter the View name:

Add View Wizard

Step 3: Replace the boilerplate code with the following code:

  1. @model IList<FbFriendsApp.Models.FacebookViewModel>  
  2. @{  
  3.     ViewBag.Title = "Facebook Friends";  
  4. }  
  5. <h2>My Facebook Friends</h2>  
  6. @if (Model.Count > 0)  
  7. {  
  8.     <div class="row">  
  9.         @foreach (var MyFriend in Model)  
  10.         {  
  11.             <div class="col-md-3">  
  12.                 <a href="#" class="thumbnail">  
  13.                     <img [email protected] [email protected] />  
  14.                 </a>  
  15.             </div>  
  16.         }  
  17.     </div>  
  18. }  

Access Application

Use the following procedure to run the application.

Step 1: Click on the LogIn link on your Home Page:

Mvc Application Login

Step 2: Click on Facebook to proceed.

Application LogIn With Facebook

Step 3: Enter the Facebook Credentials.

Facebook Credentials

Step 4: Authenticate the Facebook App.

Facebook App Authentication

Step 5: Register yourself and click on the Facebook Friends to proceed.

Facebook Provider

Step 6: Now you can view your Facebook Friends in your Web Application.

Facebook Friends

Step 7: Please log off.

That's it.

Summary

This article will help you to access social providers such as Facebook in your ASP.NET Web Application. You can also create views to display them in a sleek way. Thanks for reading.


Similar Articles