In this article we will learn to implement facebook
authentication in ASP.NET MVC web application. We know that OAuth is an
authorization protocol – or in others, a set of rules – that allow a
third-party website or application to access a user’s data without the user
needing to share login credentials.
OAuth’s open-source protocol enables user to share their
data and resource stored on one site with another site under a secure
authorization scheme based on a token-based authorization mechanism.
As this is not targeted to discuss Oauth mechanism, I will recommend
you to pick few good article to learn OAuth and it’s mechanism.
In this article we will implement OAuth using Facebook . Nuget package provide package to implement
Facebook authentication for ASP.NET. Just search for below package and install
it in application.
Once, it has install, we will find the reference in reference
folder, just like below.
First of all we have to create one application in Facebook
which will provide App ID and App Secret to our application. Those credential
will user for login.
To create app in Facebook , just login to below url.
Create one Web application with proper name, in my case I have
given OAuthTest.
Once you create the application, you should see above screen
which will provide App ID and App Secret.
Fine, now we will create “AccountController” and will write
code for Facebook authentication.
Add property in
AccountController
Here, we will add property called RedirectUri which will
return Uri, the property contains only get means there is no way to set the
property value.
private Uri RedirectUri
{
get
{
var uriBuilder = new UriBuilder(Request.Url);
uriBuilder.Query = null;
uriBuilder.Fragment = null;
uriBuilder.Path = Url.Action("FacebookCallback");
return uriBuilder.Uri;
}
}
Add Action to handle
Authentication
Here, we will create two actions which will deal with
authentication mechanism. The first one is Facebook action.
[AllowAnonymous]
public ActionResult Facebook()
{
var fb = new FacebookClient();
var loginUrl = fb.GetLoginUrl(new
{
client_id = "CLIENT
ID",
client_secret = "CLIENT SECRET",
redirect_uri = RedirectUri.AbsoluteUri,
response_type = "code",
scope = "email"
});
return Redirect(loginUrl.AbsoluteUri);
}
And the next one is FacebookCallback()
which will execute after authentication. Here is the implementation.
public ActionResult FacebookCallback(string code)
{
var fb = new FacebookClient();
dynamic result = fb.Post("oauth/access_token", new
{
client_id = "CLIENT ID",
client_secret = "SECRET",
redirect_uri = RedirectUri.AbsoluteUri,
code = code
});
var accessToken = result.access_token;
// Store the access token in the session for farther use
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, like email, first name,
middle name etc
dynamic me = fb.Get("me?fields=first_name,middle_name,last_name,id,email");
string email = me.email;
string firstname = me.first_name;
string middlename = me.middle_name;
string lastname = me.last_name;
// Set the auth cookie
FormsAuthentication.SetAuthCookie(email,
false);
return RedirectToAction("Index", "Home");
}
If we put together all stuffs within Account controller the
code is something like below.
namespace FacebookAuth.Controllers
{
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;
}
}
[AllowAnonymous]
public ActionResult login()
{
return View();
}
public ActionResult logout()
{
FormsAuthentication.SignOut();
return View("Login");
}
[AllowAnonymous]
public ActionResult Facebook()
{
var fb = new FacebookClient();
var loginUrl = fb.GetLoginUrl(new
{
client_id = "444195149059600",
client_secret = "89223ca2d87cc4a741000d5c1ea57694",
redirect_uri = RedirectUri.AbsoluteUri,
response_type = "code",
scope = "email" // Add other permissions as
needed
});
return Redirect(loginUrl.AbsoluteUri);
}
public ActionResult FacebookCallback(string code)
{
var fb = new FacebookClient();
dynamic result = fb.Post("oauth/access_token", new
{
client_id = "444195149059600",
client_secret = "89223ca2d87cc4a741000d5c1ea57694",
redirect_uri = RedirectUri.AbsoluteUri,
code = code
});
var accessToken = result.access_token;
// Store the access token in the session for farther use
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,middle_name,last_name,id,email");
string email = me.email;
string firstname = me.first_name;
string middlename = me.middle_name;
string lastname = me.last_name;
// Set the auth cookie
FormsAuthentication.SetAuthCookie(email,
false);
return RedirectToAction("Index", "Home");
}
}
}
In controller, we have included both login and logout actions
which will return the login page and signout in Form authentication simultaneously.
Enable
Form authentication
Now, we will enable form authentication, as we have implemented
same in application. Just add below tags in web.config file of application.
<authentication mode="Forms">
<forms loginUrl="~/Account/login"></forms>
</authentication>
Create
login view
Here, we will create login view to hit Facebook action which has
defined within Account controller. The view is extremely simple.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
</head>
<body>
<div>
<h2>Login</h2>
@Html.ActionLink("Login with Facebook.", "Facebook","Account")
</div>
</body>
</html>
Once we run the application and hit login action within Account
controller, we should see below view.
Once we click on link, it will perform the authentication process
and we are seeing that the data has come from Facebook.
Border
Line:
In this article we have learned to implement Facebook
authentication in ASP.NET MVC application. Hope you have understood the concept
. Open authentication / social authentication is meaningful when your
application is somehow related to social platform and when you don’t want to save
user’s sensitive password information in your application.
No comments:
Post a Comment