ASP.NET MVC Authentication Using Facebook’s C# SDK
In this sample application, ASP.NET MVC 4 RC and .NET/C# 4.0 versions were used.
Facebook Application
Create first a Facebook application on http://developers.facebook.com/apps, click the “Create New App” and follow the instructions. Take note of App ID and App Secret values for this will be needed later on.
Nuget
Facebook C# SDK is installed using Nuget. If you currently have Nuget, you should download and install it. If you already have one installed, please make sure that it is the latest version.
ASP.NET MVC 4 Website
On your visual studio 2010, create a new ASP.NET MVC website. Install Facebook C# SDK by going to Tools -> Library Package Manager -> Package Manager Console. This will open a window. On the window, type “Install-Package Facebook”. This may take a while depending on your connection. After installing, it will show you some information about the SDK and its version. The version used in this sample is “Facebook 6.0.20″. This can also be done by right clicking the projects References folder and select “Manage Nuget Packages…”. Search for the Facebook package and install it.
Facebook App Configuration
Now that C# Facebook SDK is installed and the website was set up, the site URL on the Facebook app should be modified. This must match the URL you are using on your development machine. This URL should be, http://localhost:##### where ##### is the port number on local machine.
Authenticating Site Users with Facebook
On the ASP.NET MVC website template, when a user attempts to log in, it will load a log on page where the user will input the username and password. On this sample application, when the user clicks on the login link, it will redirect them to Facebook for authentication. This will load the Facebook login page and after successfully authenticating, the user will be asked to authorize your app. After authorization, Facebook will redirect back to your site with a token that denotes the authenticated Facebook Session.
This Session Token is needed to request for an Access Token from Facebook’s Graph API Service. After obtaining the Access Token, you can query the some of the users information like UserId or UserName by using the Graph API.
How it was done
1. Create a Controller Action that Redirects to Facebook
The action should redirect to Facebook’s URL: https://graph.facebook.com/oauth/authorize. There are 3 necessary query strings that must be included with this URL:
- client_id: your Facebook’s Application ID.
- redirect_uri: URI that Facebook will redirect to after successful authentication. This must be prefixed with the Site URL that has been provided on Facebook and is case sensitive. The redirect_uri will be a controller action in our ASP.NET MVC site.
- type: user_agent or web_server. We will be using web_server for we are not authenticating asynchronously via javascript.
This is the code of our controller that handles the redirect to Facebook:
[AllowAnonymous]
public ActionResult FacebookLogin()
{
return new RedirectResult("https://graph.facebook.com/oauth/authorize? type=web_server& client_id=492401047441790& redirect_uri=http://localhost:56898/account/FacebookLoginOK");
}
We have the AllowAnonymous attribute added so the user can access this controller even if the it is not yet authenticated.
On our _LoginPartial.cshtml partial page under the views/shared folder we will modify the login link to:
<li>@Html.ActionLink("Log in", "FacebookLogin", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
When clicking the login link on the upper right side of the main page, this will go to the controller which in turn will redirect to Facebook. Facebook’s login page will be shown and after successfully authenticating, will be redirected to the URI specified on redirect_uri on controller code above.
2. Handle the Redirect from Facebook
We will now create a controller as mentioned on the redirect_uri above to handle the redirect.
Our main goal is to have the Facebook user’s username or userid. To do that, we will use the Facebook C# SDK’s FacebookClientClass with our access token.
Here is the code.
[AllowAnonymous]
public ActionResult FacebookLoginOK(string code)
{
//parameter code is the session token
if (!string.IsNullOrEmpty(code))
{
var appId = "492401047441790";
var appSecret = "8a16ff46000eb9725704487877741655";
//URL to access for the access token
string url = "https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}";
//redirectUri must be the same URI that initiates the initial authentication call. in this case,
// this controller action
string redirectUri = "http://localhost:56898/account/FacebookLoginOK";
//Create and perform a request using the URI
WebRequest request = WebRequest.Create(string.Format(url, appId, redirectUri, appSecret, code));
//Read the response as UTF-8 and parse out the access token.
//Note that the result has access token and expires parameter.
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader streamReader = new StreamReader(stream, encode);
string result = streamReader.ReadToEnd();
result = result.Remove(result.IndexOf("&expires"));
string accessToken = result.Replace("access_token=", "");
streamReader.Close();
response.Close();
//Instantiate a new facebookClient from the C# SDK with the accessToken as parameter.
var client = new FacebookClient(accessToken);
//This will return a JSON object with similar format like:
//{
// id: "10000000",
// name: "Blah Blah",
// first_name: "Blah",
// last_name: "Blah",
// link: "https://www.facebook.com/blahblah",
// username: "blah",
// gender: "male",
// locale: "en_US"
//}
//Uses a dynamic variable to handle the JSON result
dynamic me = client.Get("me");
//Can now have the value from the dynamic expression
string username = me.username;
//Authenticate the user in your site.
FormsAuthentication.SetAuthCookie(me.username, false);
}
return RedirectToAction("Index", "Home");
}
User is now authenticated and can now use any resource provided by the Graph API in this link https://developers.facebook.com/docs/reference/api/. All entities returned for the Graph Api are JSON objects so you can use dynamic data type like above.
I could not do this blog if I have not read http://amirrajan.net/Blog/asp-mvc-and-facebook-single-sign-on and http://csharpsdk.org/docs/web/getting-started. More powers to the authors!!!