Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save weedkiller/275c07c5bb74c2d6428b59770dd820c3 to your computer and use it in GitHub Desktop.
Save weedkiller/275c07c5bb74c2d6428b59770dd820c3 to your computer and use it in GitHub Desktop.
Facebook Authentication with the Facebook C# SDK and ASP.NET MVC 4
public ActionResult FacebookCallback(string code)
{
var fb = new FacebookClient();
dynamic result = fb.Post("oauth/access_token", new
{
client_id = "your_app_id_here",
client_secret = "your_app_secret_here",
redirect_uri = RedirectUri.AbsoluteUri,
code = code
});
var accessToken = result.access_token;
// TODO: Authenticate User
}
public ActionResult FacebookCallback(string code)
{
var fb = new FacebookClient();
dynamic result = fb.Post("oauth/access_token", new
{
client_id = "444977858884680",
client_secret = "0e82b0d234a172df378b10929a65fef1",
redirect_uri = RedirectUri.AbsoluteUri,
code = code
});
var accessToken = result.access_token;
// Store the access token in the session
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,last_name,id,email");
string email = me.email;
// Set the auth cookie
FormsAuthentication.SetAuthCookie(email, false);
return RedirectToAction("Index", "Home");
}
public ActionResult Login()
{
return View();
}
public class AccountController : Controller
{
//
// GET: /Auth/
public ActionResult Facebook()
{
throw new NotImplementedException();
}
}
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;
}
}
public ActionResult Facebook()
{
var fb = new FacebookClient();
var loginUrl = fb.GetLoginUrl(new {
client_id = "your_app_id_here",
redirect_uri = RedirectUri.AbsoluteUri,
response_type = "code",
scope = "email" // Add other permissions as needed
});
return Redirect(loginUrl.AbsoluteUri);
}
}
[Authorize]
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
}
@{
ViewBag.Title = "Login";
}
<h2>Login</h2>
@Html.ActionLink("Login with Facebook", "Facebook")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment