Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prabirshrestha/1065453 to your computer and use it in GitHub Desktop.
Save prabirshrestha/1065453 to your computer and use it in GitHub Desktop.
Facebook Connect with ASP.NET MVC
public class AccountController : Controller
{
public ActionResult Login(string returnUrl, string scope)
{
if (!Url.IsLocalUrl(returnUrl))
{
returnUrl = "/";
}
ViewData["returnUrl"] = returnUrl;
ViewData["scope"] = scope;
return View();
}
}
public class FacebookJsAuthorizeAttribute : FacebookAuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext, IFacebookApplication facebookApplication)
{
var authorizer = new FacebookWebContext(facebookApplication, filterContext.HttpContext);
if (!string.IsNullOrEmpty(Permissions) && Permissions.IndexOf(" ") != -1)
{
throw new ArgumentException("Permissions cannot contain whitespace.");
}
if (!authorizer.IsAuthorized(string.IsNullOrEmpty(Permissions) ? null : Permissions.Split(',')))
{
var sb = new StringBuilder();
sb.Append("~/Account/Login");
sb.AppendFormat("?returnUrl={0}", HttpUtility.UrlEncode(filterContext.RequestContext.HttpContext.Request.RawUrl));
sb.AppendFormat("&scope={0}", HttpUtility.UrlDecode(Permissions));
filterContext.Result = new RedirectResult(sb.ToString());
}
}
}
<div id="fb-root">
</div>
<script src="http://connect.facebook.net/en_US/all.js" type="text/javascript"></script>
<script type="text/javascript">
FB.init({
appId: '@Facebook.FacebookApplication.Current.AppId', cookie: true, status: true, xfbml: true
}, "/xd_receiver.htm");
FB.Event.subscribe('auth.login', function () {
window.location = '@ViewData["returnUrl"]';
});
</script>
<fb:login-button @if (!string.IsNullOrWhiteSpace((string)ViewData["scope"])){<text>perms="@ViewData["scope"]"</text>}>Login to Facebook</fb:login-button>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><body> <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/XdCommReceiver.js" type="text/javascript"></script></body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment