Tuesday, 29 November 2016

How to login with facebook in ASP.Net MVC with Source Code



Introduction:
 Here I will explain how to login with Facebook in Asp.net MVC. You can also save Facebook retrieved data to your database or show them to your website. For using Facebook API in your website firstly create account in Facebook Developer and retrieve App key and App Secrete key to use in this example
Description:

In previous articles I will explain How to login with Gmail in Asp.net MVC. Today I will explain how to login with Facebook in Asp.net  MVC. It is the most communally used authentication process in present day, It provide the facility to the user registration in just simple few simple steps.



In Asp.net MVC we implement Login with Facebook by fallowing Steps:
Step1:  Add Facebook Nuget Package

In first step we need to add Facebook Nuget Package, Right click on References and choose Manage Nuget Packages then It’s open fallowing window, Search Facebook  and select it
Facebook package will add in your references section as like this

Step2: Write fallowing code in HomeController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Facebook;
using Newtonsoft.Json;
using System.Web.Security;
namespace FaceboolLoginMVC.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

        private Uri RediredtUri
        {
            get
            {
                var uriBuilder = new UriBuilder(Request.Url);
                uriBuilder.Query = null;
                uriBuilder.Fragment = null;
                uriBuilder.Path = Url.Action("FacebookCallback");
                return uriBuilder.Uri;
            }
        }

    [AllowAnonymous]
        public ActionResult Facebook()
        {
            var fb = new FacebookClient();
            var loginUrl = fb.GetLoginUrl(new
            {

                client_id = "Your App ID",
                client_secret = "Your App Secret key",
                redirect_uri= RediredtUri.AbsoluteUri,
                response_type="code",
                scope="email"
               
            });
            return Redirect(loginUrl.AbsoluteUri);
        }

        public ActionResult FacebookCallback(string code)
    {
        var fb = new FacebookClient();
        dynamic result = fb.Post("oauth/access_token", new
            {
                client_id = "Your App ID",
                client_secret = "Your App Secret key",
                redirect_uri = RediredtUri.AbsoluteUri,
                code = code

            });
        var accessToken = result.access_token;
        Session["AccessToken"] = accessToken;
        fb.AccessToken = accessToken;
        dynamic me = fb.Get("me?fields=link,first_name,currency,last_name,email,gender,locale,timezone,verified,picture,age_range");
        string email = me.email;
        TempData["email"] = me.email;
        TempData["first_name"] = me.first_name;
        TempData["lastname"] = me.last_name;
        TempData["picture"] = me.picture.data.url;
        FormsAuthentication.SetAuthCookie(email, false);
        return RedirectToAction("Index", "Home");
    }

    }
}

Step3: Find your App ID and App Secrete

 Find your App ID and App Secret from Facebook Developer Account
Enter that App ID and App Secret in fallowing code section
                client_id = "Your App ID",
                client_secret = "Your App Secret key",

Step4: Add Index View
 Write fallowing code to access data in Index page

<div>
        @Html.ActionLink("Login with facebook", "Facebook", "Home")
        <table>
            <tr><td>Email:</td><td><b>@TempData["email"]</b></td></tr>
            <tr><td>First Name:</td><td><b>@TempData["first_name"]</b></td></tr>
            <tr><td>Last Name:</td><td><b>@TempData["lastname"]</b></td></tr>
            <tr><td>Picture:</td><td><b><img src="@TempData["picture"]" /></b></td></tr>
           
        </table>
    </div>

Step5:  Now debug application and get fallowing Output
 
Thanks ..

Download Full Source Code Here:

10 comments:

  1. it shows that something went wring , i already written AppID and Secret also

    ReplyDelete
  2. please check your Setting in Facebook Developer Account like Site URL
    . In my side it's working

    ReplyDelete
  3. Thank you sir it's 100% working. But when I don't to accept the facebook login when I click the cancel. The Visual got error

    ReplyDelete
  4. very useful tutorial! Thanks a lot! work very nice for me!

    ReplyDelete
  5. i have a error.plz help me...error is (The parameter redirect_uri is required). how i fix it.

    ReplyDelete
    Replies
    1. Please check that, your URL add in Valid Oauth redirect URLs Facebook developer account

      Delete
  6. Thanks for nice explanation.

    ReplyDelete
  7. Warning
    The URL can not be loaded: The domain for this URL is not included in the application domains. In order to load this URL, add all domains and subdomains of your application to the domain of the application in the configuration of your application.

    ReplyDelete

Ads Inside Post