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

Simple .NET MVC 3 web application with integrated Facebook OAuth API

By , 11 Apr 2012
 

Introduction

Before creating a .NET MVC application, we have to register the domain name that will be used for the web site at the Facebook development site: http://developers.facebook.com/setup/. After successful registration, we will have a Facebook APIKey and Facebook Secret.

Now let's create a simple ASP.NET MVC application in VS:

net_mvc_facebook_oauth/1_1.png

I will use the Facebook API button in this sample to show an alternative log in option to the user. Let's change the _LogOnPartial.cshtml file in such a way:

@if(Request.IsAuthenticated) {
    <text>Welcome <strong>@User.Identity.Name</strong>!
    [ @Html.ActionLink("Log Off", "LogOff", "Account") ]</text>
}
else {
    <fb:login-button perms="email,user_checkins" onlogin="afterFacebookConnect();" 
       autologoutlink="false" ></fb:login-button>
    <div id="fb-root" style="display:inline; margin-left:20px;"></div>
    @:[ @Html.ActionLink("Log On", "LogOn", "Account") ]
}
<script language="javascript" type="text/javascript">
    window.fbAsyncInit = function () {
        FB.init({ appId: ' -- YOUR REAL APPLICATION ID SHOUD BE HERE --', 
                  status: true, cookie: false, xfbml: true });
    };
    function afterFacebookConnect() {
        FB.getLoginStatus(function (response) {
            if (response.session) {
                window.location = "../Account/FacebookLogin?token=" + 
                       response.session.access_token;
            } else {
                // user clicked Cancel
            }
        });
    };
    $(document).ready(function () {
        if (document.getElementById('fb-root') != undefined) {
            var e = document.createElement('script');
            e.type = 'text/javascript';
            e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
            e.async = true;
            document.getElementById('fb-root').appendChild(e);
        }
    });
</script>

The following elements were added to the control:

  • Facebook login button (fb:login-button).
  • Container which will contain all Facebook scripts (div id="fb-root").
  • FB initialization script (FB.fbAsyncInit). You have to replace the sample appId value with the real one received when registering your app on the Facebook development site.
  • afterFacebookConnect - script which will be called after the user closes the Facebook login dialog window (after successful or failed login).
  • Script for loading Facebook JavaScript libraries (e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';).

After successful login, we will have the access_token value, and now we can load detailed user's info, store this info (if we need to), and authenticate the user. To do this, we will redirect the user to the Account.FacebookLogin action and pass the access_token value as a parameter to this action. So at this stage, we will implement the "FacebookLogin" action. The created action will look like this:

using System.Web.Mvc;
using System.Web.Security;
using MVCOAuth.Models;
using System.Net;
using Newtonsoft.Json.Linq;
using System;

namespace MVCOAuth.Controllers
{
    public class AccountController : Controller
    {
        [HttpGet]
        public ActionResult FacebookLogin(string token)
        {
            WebClient client = new WebClient();
            string JsonResult = client.DownloadString(string.Concat(
                   "https://graph.facebook.com/me?access_token=", token));
            // Json.Net is really helpful if you have to deal
            // with Json from .Net http://json.codeplex.com/
            JObject jsonUserInfo = JObject.Parse(JsonResult);
            // you can get more user's info here. Please refer to:
            //     http://developers.facebook.com/docs/reference/api/user/
            string username = jsonUserInfo.Value<string>("username");
            string email = jsonUserInfo.Value<string>("email");
            string locale = jsonUserInfo.Value<string>("locale");
            string facebook_userID = jsonUserInfo.Value<string>("id");

            // store user's information here...
            FormsAuthentication.SetAuthCookie(username, true);
            return RedirectToAction("Index", "Home");
        }

And that's it! We have integrated alternative Facebook authentication on the MVC site. Before login:

net_mvc_facebook_oauth/R_1.png

After successful Facebook authentication:

net_mvc_facebook_oauth/R_2.png

Hope this will be helpful for someone! 

License

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

About the Author

Semyuel87***

United States United States
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionfixmemberIgor Jas31-Mar-13 0:36 
GeneralMy vote of 5memberHeaven202017-Mar-13 23:56 
QuestionIs this work with localhost ???memberRavinder Singh Bhawer15-Mar-13 0:40 
AnswerRe: Is this work with localhost ???memberIgor Jas31-Mar-13 0:40 
GeneralMy vote of 1memberDavidOwen4-Jan-13 0:00 
GeneralMy vote of 5groupsakola8-Nov-12 21:32 
QuestionWhat is URL REDIRECTIONmemberMember 917112831-Jul-12 19:52 
GeneralMy vote of 5memberNaveenNeo16-Jul-12 1:01 
QuestionFacebook dialog just quickly pops up and closesmemberrory thompson17-May-12 6:53 
QuestionNot getting the logged in user's infomemberLockedOut16-May-12 2:39 
AnswerRe: Not getting the logged in user's infomemberGKG417-Sep-12 18:58 
GeneralRe: Not getting the logged in user's infomemberIgor Jas31-Mar-13 0:42 
QuestionFacebookId threws exceptionmemberMember 803473410-Apr-12 23:38 
AnswerRe: FacebookId threws exceptionmemberSemyuel87***11-Apr-12 7:16 
Questionit was very helpful :)memberIndesign-c36018-Feb-12 14:10 
QuestionFacebook updated to O.Auth 2.0memberkaneXtreme8-Feb-12 5:28 
GeneralThanks !!memberaditya.murthy881-Nov-11 20:54 
Questioncannot download the source codememberNicholas Naddaf28-Oct-11 10:31 
QuestionRe: cannot download the source codemembersalsafreakpr29-Dec-11 20:23 
QuestionCan't see Facebook Login buttonmemberpohjoon4-Sep-11 10:16 
AnswerRe: Can't see Facebook Login button [modified]memberSemyuel87***5-Sep-11 0:15 
GeneralRe: Can't see Facebook Login buttonmemberpohjoon6-Sep-11 6:14 
GeneralRe: Can't see Facebook Login buttonmemberSemyuel87***6-Sep-11 6:26 
GeneralRe: Can't see Facebook Login buttonmemberpohjoon7-Sep-11 6:17 
Questionsummarized and informativememberjahmani8-Jun-11 5:52 
GeneralMy vote of 5memberMonjurul Habib6-Jun-11 21:03 

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130617.1 | Last Updated 11 Apr 2012
Article Copyright 2011 by Semyuel87***
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid