Click here to Skip to main content
11,928,605 members (47,391 online)
Click here to Skip to main content
Add your own
alternative version


1 download
97 bookmarked

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

, 11 Apr 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
Integration of Facebook OAuth API with ASP.NET MVC 3 web site.


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: After successful registration, we will have a Facebook APIKey and Facebook Secret.

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


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=" + 
            } 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 + '//';
            e.async = true;

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 + '//';).

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
        public ActionResult FacebookLogin(string token)
            WebClient client = new WebClient();
            string JsonResult = client.DownloadString(string.Concat(
                   "", token));
            // Json.Net is really helpful if you have to deal
            // with Json from .Net
            JObject jsonUserInfo = JObject.Parse(JsonResult);
            // you can get more user's info here. Please refer to:
            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:


After successful Facebook authentication:


Hope this will be helpful for someone! 


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


About the Author

You may also be interested in...

Comments and Discussions

Questionfix Pin
Igor Jas31-Mar-13 1:36
memberIgor Jas31-Mar-13 1:36 
GeneralMy vote of 5 Pin
Heaven202018-Mar-13 0:56
memberHeaven202018-Mar-13 0:56 
QuestionIs this work with localhost ??? Pin
Ravinder Singh Bhawer15-Mar-13 1:40
memberRavinder Singh Bhawer15-Mar-13 1:40 
AnswerRe: Is this work with localhost ??? Pin
Igor Jas31-Mar-13 1:40
memberIgor Jas31-Mar-13 1:40 
GeneralMy vote of 1 Pin
DavidOwen4-Jan-13 1:00
memberDavidOwen4-Jan-13 1:00 
GeneralMy vote of 5 Pin
sakola8-Nov-12 22:32
groupsakola8-Nov-12 22:32 
QuestionWhat is URL REDIRECTION Pin
Member 917112831-Jul-12 20:52
memberMember 917112831-Jul-12 20:52 
GeneralMy vote of 5 Pin
NaveenNeo16-Jul-12 2:01
memberNaveenNeo16-Jul-12 2:01 
QuestionFacebook dialog just quickly pops up and closes Pin
rory thompson17-May-12 7:53
memberrory thompson17-May-12 7:53 
QuestionNot getting the logged in user's info Pin
LockedOut16-May-12 3:39
memberLockedOut16-May-12 3:39 
AnswerRe: Not getting the logged in user's info Pin
GKG417-Sep-12 19:58
memberGKG417-Sep-12 19:58 
GeneralRe: Not getting the logged in user's info Pin
Igor Jas31-Mar-13 1:42
memberIgor Jas31-Mar-13 1:42 
QuestionFacebookId threws exception Pin
Member 803473411-Apr-12 0:38
memberMember 803473411-Apr-12 0:38 
AnswerRe: FacebookId threws exception Pin
Semyuel87***11-Apr-12 8:16
memberSemyuel87***11-Apr-12 8:16 
Questionit was very helpful :) Pin
Indesign-c36018-Feb-12 15:10
memberIndesign-c36018-Feb-12 15:10 
QuestionFacebook updated to O.Auth 2.0 Pin
kaneXtreme8-Feb-12 6:28
memberkaneXtreme8-Feb-12 6:28 
GeneralThanks !! Pin
aditya.murthy881-Nov-11 21:54
memberaditya.murthy881-Nov-11 21:54 
Questioncannot download the source code Pin
Nicholas Naddaf28-Oct-11 11:31
memberNicholas Naddaf28-Oct-11 11:31 
QuestionRe: cannot download the source code Pin
salsafreakpr29-Dec-11 21:23
membersalsafreakpr29-Dec-11 21:23 
QuestionCan't see Facebook Login button Pin
pohjoon4-Sep-11 11:16
memberpohjoon4-Sep-11 11:16 
AnswerRe: Can't see Facebook Login button [modified] Pin
Semyuel87***5-Sep-11 1:15
memberSemyuel87***5-Sep-11 1:15 
GeneralRe: Can't see Facebook Login button Pin
pohjoon6-Sep-11 7:14
memberpohjoon6-Sep-11 7:14 
GeneralRe: Can't see Facebook Login button Pin
Semyuel87***6-Sep-11 7:26
memberSemyuel87***6-Sep-11 7:26 
GeneralRe: Can't see Facebook Login button Pin
pohjoon7-Sep-11 7:17
memberpohjoon7-Sep-11 7:17 
Questionsummarized and informative Pin
jahmani8-Jun-11 6:52
memberjahmani8-Jun-11 6:52 
GeneralMy vote of 5 Pin
Monjurul Habib6-Jun-11 22:03
memberMonjurul Habib6-Jun-11 22:03 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.151126.1 | Last Updated 11 Apr 2012
Article Copyright 2011 by Sem.Shekhovtsov
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid