Click here to Skip to main content
Click here to Skip to main content

Facebook Authentication using OAuth in ASP.NET MVC

, 11 Aug 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

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

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.

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.

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.

        [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.

        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.

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.

<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.

    @{
        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.

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

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)

Share

About the Author

Sourav Kayal
Software Developer TIMKEN India research Institute
India India
I am software developer from INDIA, working in manufacturing domain. Beside my day to day development work, i like to learn new technology and 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.
Follow on   LinkedIn

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150302.1 | Last Updated 11 Aug 2014
Article Copyright 2014 by Sourav Kayal
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid