Click here to Skip to main content
15,886,806 members
Articles / Web Development / HTML
Tip/Trick

Facebook Authentication using OAuth in ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.88/5 (6 votes)
11 Aug 2014CPOL2 min read 59.5K   11   10
In this tip, we are going to learn Facebook authentication in ASP.NET MVC application

Introduction

In this tip, we will learn to implement Facebook authentication in ASP.NET MVC web application. We know that OAuth is an authorization protocol – or in others, a set of rules – that allow a third-party website or application to access a user’s data without the user needing to share login credentials.

OAuth’s open-source protocol enables users to share their data and resource stored on one site with another site under a secure authorization scheme based on a token-based authorization mechanism.

As this is not targeted to discuss Oauth mechanism, I will recommend you to pick few good articles to learn OAuth and its mechanism.

In this tip, we will implement OAuth using Facebook. Nuget package provides a package to implement Facebook authentication for ASP.NET. Just search for the below package and install it in the application.

Image 1

Once it has installed, we will find the reference in reference folder, just like below.

Image 2

First of all, we have to create one application in Facebook which will provide App ID and App Secret to our application. Those credentials will be used for login.

To create an app in Facebook, just login to the below url: https://developers.facebook.com/

Create one Web application with proper name, in my case I have given OAuthTest.

Image 3

Once you create the application, you should see the above screen which will provide App ID and App Secret.

Fine, now we will create “AccountController” and write code for Facebook authentication.

Add Property in AccountController

Here, we will add property called RedirectUri which will return Uri, the property contains only get which means there is no way to set the property value.

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

Add Action to Handle Authentication

Here, we will create two actions which will deal with authentication mechanism. The first one is Facebook action.

C#
[AllowAnonymous]
public ActionResult Facebook()
{
    var fb = new FacebookClient();
    var loginUrl = fb.GetLoginUrl(new
    {
        client_id = "CLIENT ID",
        client_secret = "CLIENT SECRET",
        redirect_uri = RedirectUri.AbsoluteUri,
        response_type = "code",
        scope = "email"
    });

    return Redirect(loginUrl.AbsoluteUri);
}

And the next one is FacebookCallback() which will execute after authentication. Here is the implementation.

HTML
public ActionResult FacebookCallback(string code)
{
    var fb = new FacebookClient();
    dynamic result = fb.Post("oauth/access_token", new
    {
        client_id = "CLIENT ID",
        client_secret = "SECRET",
        redirect_uri = RedirectUri.AbsoluteUri,
        code = code
    });

    var accessToken = result.access_token;

    // Store the access token in the session for farther use
    Session["AccessToken"] = accessToken;

    // update the facebook client with the access token so
    // we can make requests on behalf of the user
    fb.AccessToken = accessToken;

    // Get the user's information, like email, first name, middle name etc
    dynamic me = fb.Get("me?fields=first_name,middle_name,last_name,id,email");
    string email = me.email;
    string firstname = me.first_name;
    string middlename = me.middle_name;
    string lastname = me.last_name;

    // Set the auth cookie
    FormsAuthentication.SetAuthCookie(email, false);
    return RedirectToAction("Index", "Home");
}

If we put together all stuff within Account controller, the code is something like below.

C#
namespace FacebookAuth.Controllers
{
    public class AccountController : Controller
    {
        private Uri RedirectUri
        {
            get
            {
                var uriBuilder = new UriBuilder(Request.Url);
                uriBuilder.Query = null;
                uriBuilder.Fragment = null;
                uriBuilder.Path = Url.Action("FacebookCallback");
                return uriBuilder.Uri;
            }
        }

        [AllowAnonymous]
        public ActionResult login()
        {
            return View();
        }

        public ActionResult logout()
        {
            FormsAuthentication.SignOut();
            return View("Login");
        }

        [AllowAnonymous]
        public ActionResult Facebook()
        {
            var fb = new FacebookClient();
            var loginUrl = fb.GetLoginUrl(new
            {
                client_id = "444195149059600",
                client_secret = "89223ca2d87cc4a741000d5c1ea57694",
                redirect_uri = RedirectUri.AbsoluteUri,
                response_type = "code",
                scope = "email" // Add other permissions as needed
            });

            return Redirect(loginUrl.AbsoluteUri);
        }

        public ActionResult FacebookCallback(string code)
        {
            var fb = new FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new
            {
                client_id = "444195149059600",
                client_secret = "89223ca2d87cc4a741000d5c1ea57694",
                redirect_uri = RedirectUri.AbsoluteUri,
                code = code
            });

            var accessToken = result.access_token;

            // Store the access token in the session for farther use
            Session["AccessToken"] = accessToken;

            // update the facebook client with the access token so 
            // we can make requests on behalf of the user
            fb.AccessToken = accessToken;

            // Get the user's information
            dynamic me = fb.Get("me?fields=first_name,middle_name,last_name,id,email");
            string email = me.email;
            string firstname = me.first_name;
            string middlename = me.middle_name;
            string lastname = me.last_name;
            
            // Set the auth cookie
            FormsAuthentication.SetAuthCookie(email, false);
            return RedirectToAction("Index", "Home");
        }
    }
}

In controller, we have included both login and logout actions which will return the login page and signout in Form authentication simultaneously.

Enable Form Authentication

Now, we will enable form authentication, as we have implemented the same in the application. Just add the below tags in web.config file of the application.

XML
<authentication mode="Forms">
      <forms loginUrl="~/Account/login"></forms>
    </authentication>

Create Login View

Here, we will create login view to hit Facebook action which has defined within Account controller. The view is extremely simple.

HTML
    @{
        Layout = null;
    }
    <!DOCTYPE html>
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        </head>
    <body>
        <div> 
            <h2>Login</h2>
            @Html.ActionLink("Login with Facebook.", "Facebook","Account")
        </div>
    </body>
</html>

Once we run the application and hit login action within Account controller, we should see the below view.

Image 4

Once we click on link, it will perform the authentication process and we are seeing that the data has come from Facebook.

Image 5

Border Line

In this tip, we have learned to implement Facebook authentication in ASP.NET MVC application. Hope you have understood the concept. Open authentication / social authentication is meaningful when your application is somehow related to social platform and when you don’t want to save user’s sensitive password information in your application.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer DELL International
India India
I am software developer from INDIA. Beside my day to day development work, i like to learn new technologies to update myself. I am passionate blogger and author in various technical community including dotnetfunda.com , c-sharpcorner.com and codeproject. My area of interest is modern web technology in Microsoft stack. Visit to my personal blog here.

http://ctrlcvprogrammer.blogspot.in/

Comments and Discussions

 
Questioni am able to login in facebbok but redirection is not working proper. Pin
Member 920227715-Oct-18 3:45
Member 920227715-Oct-18 3:45 
QuestionFacebookClient() file missing. Pin
Member 1352025516-Jan-18 0:23
Member 1352025516-Jan-18 0:23 
Questiongetting leads ads from webhook Pin
Fannie08222-Aug-17 3:47
Fannie08222-Aug-17 3:47 
QuestionError occured Pin
Member 1026427916-Feb-17 22:10
professionalMember 1026427916-Feb-17 22:10 
QuestionGoogle Login Pin
Ale Guzman31-Aug-16 8:13
Ale Guzman31-Aug-16 8:13 
Questionnot redirecting to FB login page Pin
Uday Vishwakarma4-Feb-16 2:04
Uday Vishwakarma4-Feb-16 2:04 
QuestionHow you can redirect to previous page? Pin
DucHoang26-Jul-15 22:00
DucHoang26-Jul-15 22:00 
QuestionCan use this function for Account Facebook they using phone login? Pin
DucHoang26-Jul-15 21:05
DucHoang26-Jul-15 21:05 
QuestionFacebook callback is not working proper Pin
chandraprakashkabra24-Apr-15 19:37
professionalchandraprakashkabra24-Apr-15 19:37 
Hi saurav,

This is very good article, and i am able to login in facebbok but redirection is not working proper.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.