Simple .NET MVC 3 web application with integrated Facebook OAuth API
1. Before creating a .Net MVC application we have to register domain name that will be used for web site at the Facebook development site http://developers.facebook.com/setup/. After successful registration we will have facebook APIKey and facebook Secret.
2. Now let's create a simple ASP.NET MVC application in VS:
I will use facebook api button in this sample to show alternative log in option to the user.
Let's change _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>
Following elements were added to the control:
- facebook login button (fb:login-button) here,
- container which will contain all facebook scripts (div id="fb-root")
- FB initialization script (FB.fbAsyncInit). You HAVE TO replace sample appId value with real one, received when registering your app on the facebook development site.
- afterFacebookConnect - script which will be called after user closed FB login dialog window, (after successful or failed login)
- script for loading FB javascript libraries (e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';)
After successful login we will have 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 user to the Account.FacebookLogin action, and pass access_token value as a parameter to this action. So at this stage we will implement "FacebookLogin" action.
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");
int facebook_userID = jsonUserInfo.Value<int>("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!
Sam
Post Comment
GTV9ci Very good article.Really thank you! Much obliged.
m7HThq Some really fantastic info , Gladiolus I detected this.
cgvkD0 I think this is a real great post. Will read on
kNsLpJ You might be my role models. Many thanks for the write-up
sk5R5H Thanks for sharing, this is a fantastic article.Thanks Again.
q9YtgT A round of applause for your post.Much thanks again. Much obliged.
rTsiVt great post, very informative. I wonder why the other specialists of this sector don't notice this. You must continue your writing. I'm sure, you've a huge readers' base already!
ruXPVc Terrific post however I was wanting to know if you could write a litte more on this topic? I'd be very grateful if you could elaborate a little bit further. Kudos!
7WaPH6 Of course, what a splendid site and revealing posts, I surely will bookmark your website.Have an awsome day!
KTeab8 whoah this blog is great i like studying your articles. Keep up the good work! You know, lots of persons are searching round for this info, you can aid them greatly.
U99mmY Nice blog here! Also your web site loads up very fast! What host are you using? Can I get your affiliate link to your host? I wish my web site loaded up as quickly as yours lol
zQf85M Thanks for the post.Really thank you! Will read on...
UN9bXX excellent submit, very informative. I wonder why the other experts of this sector don't realize this. You should proceed your writing. I am confident, you have a huge readers' base already!
y1xt0u Major thanks for the article.Thanks Again. Fantastic.
ly9mhW I loved your blog.Much thanks again. Fantastic.
fCCu6A Hey, thanks for the article post.Much thanks again. Awesome.
tFKbeq Thank you for your blog article.Really thank you! Much obliged.
MqLbUb Thanks for the blog.Much thanks again. Keep writing.
ywsDEV I truly appreciate this blog article.Really thank you! Really Cool.
6PGNk5 Really informative blog article.Really looking forward to read more. Much obliged.
7wkxZr This is one awesome post.Thanks Again. Keep writing.
culo0W Great blog article.Much thanks again. Really Cool.
mFkBnh Very good post.Thanks Again. Great.
8RZmXV Im obliged for the blog post. Fantastic.