Login to your website through Facebook

By | March 12, 2011
In this post we will see how to login to your website using facebook id. Facebook is giving this option to developers so that users of our website can avoid multiple registrations.

Steps to follow:

  • Create a facebook application.
  • Your app details will be displayed. Click on ‘Edit Settings’. Select ‘Web Site’ tab from left pane and fill details.
  • ‘Site URL’ should in the format http://www.techbana.com and ‘Site Domain’ should be in the format ‘techbana.com’. These values ensures that login control validates request only from techbana.com. If somebody else is copying my code it wont work in their website as the appid is connected with this particular domain.
  • Click on ‘Save Changes’. Now the settings which has to be configured in facebook site is over.

Lets create a new webpage for our website for authentication test.

<html>
<head>
<title>Try facebook Login</title>
</head>
<body>
<div id=”fb-root”></div>
<script src=”http://connect.facebook.net/en_US/all.js”></script>
<script>
FB.init({
appId:’YOUR_APP_ID’, cookie:true,
status:true, xfbml:true
});
FB.getLoginStatus(function(response) {
if (response.session) {

var profileDetails=document.getElementById(‘profileInfo’);
profileDetails.style.display=’block’;
FB.api(‘/me’, function(userData) {
if(userData != null) {
var image = document.getElementById(profileImage’);
image.src = ‘http://graph.facebook.com/’ + userData.id + ‘/picture’;
var name = document.getElementById(‘userName’);
name.innerHTML = userData.name
}
});
} else {
// no user session available, someone you dont know
var logButton = document.getElementById(‘loginButton’);
logButton.style.display = ‘block’;
}
});
function faceLogout()
{
FB.logout(function(response) {
// user is now logged out
window.location.href=window.location.href;
});
}
function faceLogin()
{
FB.login(function(response) {
if (response.session) {
window.location.href=window.location.href;
} else {
document.write(‘cancelled login’);
}
});
}
</script>
<div id=”loginButton” style=”display: none”>
<button onClick=”faceLogin()”>Login with Facebook</button>
</div>
<div align=”left” id=”profile” style=”display: none;”>
<img id=”profileImage”/>
<div id=”userName”></div>
<button id=”logoutButton” onClick=”faceLogout()”>Logout</button>
</div>
</body>
</html>

One thought on “Login to your website through Facebook

  1. Pingback: how to unplug a milk duct