Download Sample Project
In previous post,
Use Facebook login in MVC, i discussed how you can use Facebook to authenticate
users in your web application. Authentication implementation will not be complete without
providing the user a way to logout out of the application. In this post I will show how to
implement Facebook logout button in your MVC application.
Facebook Logout Button or Link
If you have not tried our application running on MVC4 (Developed with VS11), try
Facebook login here Universal Shopping Mall.
Once you will login, you will see logout button appear in top right side of the page as
shown in image below.
Facebook Logout Controller and Action
Here is documentation from Facebook developer site about programmatically logging
user out of Facebook.
You can programmatically log the user our of Facebook by redirecting the user to
The URL supplied in the next parameter must be a URL with the same base domain as your application as defined in your app's settings.
This means when we send request to Facebook to log out user, it is going to
call back on URL specified in next parameter. You will need
to implement a controller to receive this call back from Facebook. Following
snippet shows how I have set up a link for logout.
@Html.ActionLink("Logout", "Logout", "Account")
This means I have implemented an action Logout in my
Account controller. This is same controller where I added
Login action to perform login. Following code snippet shows implementation
of this Logout action in demo application.
public ActionResult Logout()
var fbUser = Session["fbUser"] as Models.FacebookUser;
if (null == fbUser)
return new RedirectResult(Request.UrlReferrer.AbsoluteUri);
var redirectUrl = string.Format("https://www.facebook.com/logout.php?
//TODO: Do book keeping about this Facebook user's activity.
Session["fbUser"] = null;
return new RedirectResult(redirectUrl);
You will notice that I have done following things before sending logout request to
Facebook for this user.
- Called FormsAuthentication.SignOut to remove authentication cookie for this
user from the application.
Invalidated session variable containing this user's information. You can also
call Session.Abandon at this stage to clear all session variables.
Once request returns from Facebook, the login button appears instead of logout
Demo and Sample Project
I have attached sample project with this post. You will need to replace
your Facebook application information in web.config file. And you can see this
all in action in real production application as Universal Shopping Mall.