When you create a New ASP.NET Project in VS 2013 and choose Individual Accounts, the template shows how you can login with Social providers such as Microsoft Account, Facebook, Google and Twitter. When you login with these Social Providers such as Facebook, you can request more information about the user such as the User’s picture, friends etc. and if the user allows your app to access this data then you can get this information and provide a rich experience in your site.
In the following post I am going to show you how you can request more data (or scopes) when a user logs in via Facebook provider. This post assumes that you have enabled Facebook login and are familiar with the basic walkthrough of Facebook Login. You can visit http://www.asp.net/mvc/tutorials/mvc-5/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on to see a basic walkthrough on how to enable Facebook Login in the template.
[Update]: You can find the completed sample at https://github.com/rustd/FBLogin
Following are the steps to get more scopes from Facebook
- In Visual Studio 2013, create ASP.NET MVC application with Individual Authentication selected.
- Enable Facebook Login by getting the keys from Facebook as show in http://www.asp.net/mvc/tutorials/mvc-5/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on
- Modify the following code in StartupAuth.cs to request more scopes as shown below.
- Â var x = new FacebookAuthenticationOptions();
- Â x.Scope.Add("email");
- Â x.Scope.Add("friends_about_me");
- Â x.Scope.Add("friends_photos");
- Â x.AppId = "YourAppId";
- Â x.AppSecret = "YourAppSecret";
- Â x.Provider = new FacebookAuthenticationProvider()
- {
- Â Â Â Â OnAuthenticated = async context =>
- Â Â Â Â {
- Â Â Â Â Â Â Â Â //Get the access token from FB and store it in the database and
- Â Â Â Â Â Â Â Â //use FacebookC# SDK to get more information about the user
- Â Â Â Â Â Â Â Â context.Identity.AddClaim(
- Â Â Â Â Â Â Â Â new System.Security.Claims.Claim("FacebookAccessToken",
- Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â context.AccessToken));
- Â Â Â Â }
- };
- Â x.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;
- Â app.UseFacebookAuthentication(x);
- Line 2-5, we are specifying the scopes.
- Line 9-15, we are hooking to the OnAuthenticated event for the Facebook OWIN authentication middleware. This method is called each time a user authenticates with Facebook.
When the user is authenticated and has granted this app access to this data, all the data is stored in the FacebookContext in the Facebook authentication middleware. - Line 14, also stores the FacebookAccessToken which we get from Facebook and which we will use to get the Users’ friends information
Store the FacebookAccessToken and use it in the app to get the list of friends and their pictures
-
Add a link in _LoginPartial.cshtml to display pictures of all friends
-
Code Snippet
- <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
- <li>
- Â Â Â Â Â Â Â Â Â @Html.ActionLink("FacebookInfo", "FacebookInfo", "Account")
- Â Â Â Â
- </li>
- Get the FacebookAccessToken claim and store it in the UserClaims table using ASP.NET Identity
- In the following code we get the Claim which was passed from Facebook Middleware to the app
- StoreFacebookAuthToken gets the claims from the UserIdentity and persists the AccessToken in the database as a User Claim.
- LinkLoginCallback action is called when the user is logged in and is associating another login provider.
- //
- // GET: /Account/LinkLoginCallback
- publicasyncTask<ActionResult> LinkLoginCallback()
- {
- var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId());
- if (loginInfo == null)
- {
- return RedirectToAction("Manage", new { Message = ManageMessageId.Error });
- }
- var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login);
- if (result.Succeeded)
- {
- var currentUser = await UserManager.FindByIdAsync(User.Identity.GetUserId());
- //Add the Facebook Claim
- await StoreFacebookAuthToken(currentUser);
- return RedirectToAction("Manage");
- }
- return RedirectToAction("Manage", new { Message = ManageMessageId.Error });
- }
- ExternalLoginConfirmation action is called when you login with the Facebook provider for the first time.
- In Line 26, once the User is created we add a new line to add the FacebookAccessToken as a claim for the user.
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- publicasyncTask<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
- {
- if (User.Identity.IsAuthenticated)
- {
- return RedirectToAction("Manage");
- }
- if (ModelState.IsValid)
- {
- // Get the information about the user from the external login provider
- var info = await AuthenticationManager.GetExternalLoginInfoAsync();
- if (info == null)
- {
- return View("ExternalLoginFailure");
- }
- var user = newApplicationUser() { UserName = model.Email };
- var result = await UserManager.CreateAsync(user);
- if (result.Succeeded)
- {
- result = await UserManager.AddLoginAsync(user.Id, info.Login);
- if (result.Succeeded)
- {
- await StoreFacebookAuthToken(user);
- await SignInAsync(user, isPersistent: false);
- return RedirectToLocal(returnUrl);
- }
- }
- AddErrors(result);
- }
- ViewBag.ReturnUrl = returnUrl;
- return View(model);
- }
- ExternalLoginCallback action is called when you associate the User with an external login provider for the first time.
- In line 17 we add a new line to add the FacebookAccessToken as a claim for the user.
- //
- // GET: /Account/ExternalLoginCallback
- [AllowAnonymous]
- publicasyncTask<ActionResult> ExternalLoginCallback(string returnUrl)
- {
- var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
- if (loginInfo == null)
- {
- return RedirectToAction("Login");
- }
- // Sign in the user with this external login provider if the user already has a login
- var user = await UserManager.FindAsync(loginInfo.Login);
- if (user != null)
- {
- //Save the FacebookToken in the database if not already there
- await StoreFacebookAuthToken(user);
- await SignInAsync(user, isPersistent: false);
- return RedirectToLocal(returnUrl);
- }
- else
- {
- // If the user does not have an account, then prompt the user to create an account
- ViewBag.ReturnUrl = returnUrl;
- ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
- return View("ExternalLoginConfirmation", newExternalLoginConfirmationViewModel { Email = loginInfo.Email });
- }
- }
-
This stores the FacebookAccessToken as a User Claim in the ASP.NET Identity database
- privateasyncTask StoreFacebookAuthToken(ApplicationUser user)
- {
- var claimsIdentity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
- if (claimsIdentity != null)
- {
- // Retrieve the existing claims for the user and add the FacebookAccessTokenClaim
- var currentClaims = await UserManager.GetClaimsAsync(user.Id);
- var facebookAccessToken = claimsIdentity.FindAll("FacebookAccessToken").First();
- if (currentClaims.Count() <=0 )
- {
- await UserManager.AddClaimAsync(user.Id, facebookAccessToken);
- }
- Install the Facebook C#SDK NuGet package. http://nuget.org/packages/Facebook
- Add the following code in AccountViewModel
- Â Â Â public class FacebookViewModel
- Â Â {
- Â Â Â Â Â Â Â [Required]
- Â Â Â Â Â Â Â [Display(Name = "Friend's name")]
- Â Â Â Â Â Â Â public string Name { get; set; }
- Â Â Â Â Â Â Â public string ImageURL { get; set; }
- Â Â Â }
- Add the following Action in the Account Controller. This action gets the FacebookAccessToken and makes a call to Facebook using Facebook C# SDK to get the list of friends and their pictures.
- //GET: Account/FacebookInfo
- [Authorize]
- publicasyncTask<ActionResult> FacebookInfo()
- {
- var claimsforUser = await UserManager.GetClaimsAsync(User.Identity.GetUserId());
- var access_token = claimsforUser.FirstOrDefault(x => x.Type == "FacebookAccessToken").Value;
- var fb = newFacebookClient(access_token);
- dynamic myInfo = fb.Get("/me/friends");
- var friendsList = newList<FacebookViewModel>();
- foreach (dynamic friend in myInfo.data)
- {
- friendsList.Add(newFacebookViewModel()
- {
- Name = friend.name,
- ImageURL = @"https://graph.facebook.com/" + friend.id + "/picture?type=large"
- });
- }
- return View(friendsList);
- }
- Add a new View FacebookInfo.cshtml under ViewsAccount and add the following markup
- @model IList<FB.Models.FacebookViewModel>
- Â Â @if (Model.Count > 0)
- Â Â {
- Â Â Â Â Â Â <h3>List of friends</h3>
- Â Â Â Â Â Â <div class="row">
- Â Â Â Â Â Â Â Â Â Â Â Â Â Â @foreach (var friend in Model)
- Â Â Â Â Â Â Â Â Â Â Â Â Â {
- Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â <div class="col-md-3">
- Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â <a href="#" class="thumbnail">
- Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â <img src=@friend.ImageURL alt=@friend.Name />
- Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â </a>
- Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â </div>
- Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â }
- Â Â Â Â Â Â </div>
- Â Â }
- Run the project and log in using Facebook. You should be taken to the Facebook Site where when you successfully login and grant this app permissions to access this data, then you should be redirected back to the application.
- When you click the FacebookInfo link, you should see your friends along with their profile pictures.
Conclusion
This was an easy way to extend the Social providers and get more information about the logged in user so you can provide a rich experience for the web site users. You can do this with the other Social Providers as well. If you have any questions, please visit the asp.net/forums or reach me via twitter (@rustd)
0 comments