Share this page with someone:
Facebook Login
Disclaimer: The code within the post is NOT ready for a production environment. I have halfway pulled it out of Codeigniter and half formatted as you would need. So this is not usable in a production environment. It is ONLY meant to serve as examples.
I had to write about this. This was probably one of the most annoying things I have had to work with in a long time. I have found a lot of people online who have had very similar problems with this. I want to try and hopefully save someone a lot of stress and heartache from having to try to figure out the Facebook registration and login by themselves. I have had about 2-3 days worth of very aggravating trial and error. I figured out a few key points and thoroughly understand how this works, inside and out.
Step One: Create App
Create a facebook account (unless you already have one). Once that is created, go into Facebook and login. At the very bottom of the page,
once you login, you will see a "Developers" link. You have to go to the very bottom of the page. Click that link. At the top right hand corner of the screen, click "My Apps". At the top right of this page click, "Set Up New App". Follow the instructions from there. It's pretty simple. Just put in all of your information, and setup the return URL as your website address. This is VERY important. So if your website is http://www.letseatcheese.com, then that is what goes in your domain and URL settings. This is a very important step. Make sure you follow the instructions on this part very carefully.
Also note..if you can't get to the create app screen, then it might be because your Facebook account isn't authorized. IF that is the case, Facebook would return an error about having to register your account (either using your mobile number, or your credit card). Perform whatever steps are needed to verify that. Once you have all of that ready, your ready to go.
That's it. You have created the app. Inside the app settings please note your app information. You will need the APP Id, Secret Key, and API Key. You will need to make note of all of these. They are very important, as is the site url and site domain. 90% of the time you have issues setting this up, it's going to come down to some of that basic information being wrong.
Step Two: Registration
The first thing you have to do is setup a way for users to assign their user account (on your site) with a facebook system. This is what allows the automatic login to occur from Facebook. There has to be some type of communication initially between Facebook and your system in order to record the Facebook User ID. This is what allows your system to match up user accounts during the login process. To be honest with you, the entire registration process is very easy.
There are a variety of ways to set this up. However, I did not want to have to fight with some of the methods they present, so I used the more straight forward Iframe. It worked for me very well. You would simply add the following code to your registration form. So you have your standard registration form (where they can register) and then you have your facebook Connect code. This code allows for standard registration, along with setting up Facebook integration (so they can do facebook login).
<iframe src="http://www.facebook.com/plugins/registration.php? client_id=APP_ID& redirect_uri=REDIRECT_URL& fields=name,email" scrolling="auto" frameborder="no" style="border:none" allowTransparency="true" width="100%" height="330"> </iframe>
This simple block of code handles the ENTIRE UI interface. This creates the box, populates all the data, and handles the entire user interface. You replace APP_ID with the ID of your application (which I explained how to get earlier). Then you replace the REDIRECT_URL with the URL of the page you want the script to send the data to. This HAS to contain the same BASE URL that was configured when you created the app (I explained this in very good detail earlier). Please make sure that URL is the same. So it would be whatever the URL you set in your Application Information, with whatever page you want. So if your website was http://www.whatever.com and the page which you were going to use the process the data was process_facebook.php then you would put the redirect URL as http://www.whatever.com/process_facebook.php. That is all that is involved in setting up the UI.
The next step, is processing the registration. This is the step that let's us match our registration system, with the facebook registration system. It's a very simple process. Let's assume the file is the same as I mentioned above..."process_facebook.php". You would have pretty much exactly what I have below in the process_facebook.php. If you were using the exact same setup as me, then this file
would be in your root folder.
define('FACEBOOK_APP_ID', 'APPID'); define('FACEBOOK_SECRET', 'SECRETKEY'); if ($_REQUEST) { $response = parse_signed_request($_REQUEST['signed_request'], FACEBOOK_SECRET); $user_data = array(); $user_data['facebook_userid'] = $response['user_id']; $user_data['facebook_connect'] = 1; $user_data['email'] = $response['registration']['email']; $name = explode(" ", $response['registration']['name']); $user_data['first_name'] = $name[0]; $user_data['last_name'] = $name[count($name)-1]; $sql = "INSERT INTO user_information (first_name, last_name, email, facebook_userid, facebook_connect) VALUES ('" . $user_data['first_name'] . "','" . $user_data['last_name'] . "','" . $user_data['email'] . "','" . $user_data['facebook_userid'] . "','" . $user_data['facebook_connect'] . "')"; if (mysql_query($sql)) { // Setup success message and redirect }else { // Setup failed message and redirect } } else { // Setup error message that request was empty } } function parse_signed_request($signed_request, $secret) { list($encoded_sig, $payload) = explode('.', $signed_request, 2); // decode the data $sig = base64_url_decode($encoded_sig); $data = json_decode(base64_url_decode($payload), true); if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') { error_log('Unknown algorithm. Expected HMAC-SHA256'); return null; } // check sig $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true); if ($sig !== $expected_sig) { error_log('Bad Signed JSON signature!'); return null; } return $data; } function base64_url_decode($input) { return base64_decode(strtr($input, '-_', '+/')); }
First replace APPID with the application ID, then replace SECRETKEY with the application secret key. Both of these can be found inside the Facebook settings which I have explained earlier. Those two functions were ones that I have taken from Facebook examples. These handle what is needed to decode the operation, and beats having to right it all from scratch.
Step Three: Login
The next and final step to this entire process is the Login script. This is what I ended up having to fight with for so long. There are a total of 2-3 steps in this process. So it is more convoluted than it originally seems. The first step is to deal with the user having to login/register or whatever else is needed. During the first step here a variety of things happen. If the User is not logged into facebook then they are prompted to login to it. If they are then it bypasses this step. Secondly, it checks if they have authorized this application to get access to their information. If they have then it skips this step, if they haven't then it prompts them to do so. So the front end flow is described below:
- User clicks link.
- If logged in then great. If not, then prompt for facebook login.
- If authorized for this app then great, if not them prompt for authorization from user
- If they decline auth, then it redirects them to fail page. If they approve or have already approved it handles Login automatically
behind the scenes
That is the general flow of this entire situation. Now let's see how all of this runs on the backend.
The first thing we need is to verify whether or not the user is currently logged into facebook, if not we need to require them to login via facebook. Facebook actually handles all of this for us. We just need to automatically point the users in the right direction. This is where we actually create our facebook link that says "Login Via Facebook" or "Connect Via Facebook" or whatever you want. The code is below:
<a href="https://graph.facebook.com/oauth/authorize?client_id=APPID&redirect_uri=REDIRECTURL">Facebook Connect</a></p>
This is where the important step comes in. The easy part is your app id. Just replace that with your app id. Now for the redirect URL. You need to put in the URL to the file that is going to process all of this. The thing is, this has to be a filename that you remember. Since we have to use this a few times...
Once they do this, it will handle their login, and authorization and everything else.
The next step is to deal with the processing using the following code (all found on facebook_connect.php in my script). So if your
redirect url is http://www.website.com/facebook_connect.php then that is where all of this code is going to go. In facebook_connect.php in your root folder on your web server.
<?php $code = $_REQUEST['code']; $url = 'https://graph.facebook.com/oauth/access_token?client_id=APPID&redirect_uri=REDIRECTURL&scope=offline_access&client_secret=APPSECRETKEY&code=' . $code; $access_code = file_get_contents($url); $url = 'https://graph.facebook.com/me?' . $access_code; $data = json_decode(file_get_contents($url)); $sql = "SELECT * FROM user_information WHERE facebook_userid = '" . mysql_real_escape_string($data->id) . "'"; $query = mysql_query($sql); while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) { $user_id = $row['user_id']; } header('Location: <a href="http://www.cheetahseat.com/index.php/fblogin/autologin/'" title="http://www.cheetahseat.com/index.php/fblogin/autologin/'">http://www.cheetahseat.com/index.php/fblogin/autologin/'</a> . $user_id); ?>
That's all there is too it. Replace the app id, and secret key with your unique information from the facebook app you created. Now here is the catch...the return url here, HAS to be the exact same as it was on the previous link. In short, EVERYTHING has to happen on this one page. If you try to do ONE step of the process with a different return URL it will not work. Make sure the return URL on this page is the
EXACT same as the one you provided in the original anchor link. Or it will not work. It'll return a strange error like cannot verify URL or something. That is pretty much everything.
Codeigniter Integration
Setting this up with Codeigniter requires an additional layer of work. Trying to perform OAuth work through CI can be a pain. I ended up working around this, in a pretty secure manner. However, you might want to clean up and tighten up the security a little bit on the login process (perhaps secondary sessions or something just to make SURE that it's really secure). I did this code pretty quickly.
So I found a very easy way to do this. Basically you just create a facebook_connect.php in your root folder (outside of codeigniter). So you have your original anchor link in one of your codeigniter views. That links with a return url of www.website.com/facebook_connect.php. Then all of my code is in there. You can access Code Igniter's database information by putting the following code at the top of the page.
define('BASEPATH', '/system/'); require_once('system/application/config/database.php'); mysql_connect($db['default']['hostname'], $db['default']['username'], $db['default']['password']); mysql_select_db($db['default']['database']);
This gives you full access to all Mysql functionality using standard mysql functions and stays connected to the Code Igniter database. Saves you a lot of time having to run all of this through a second database. Here is the trick though for Code Igniter. To make it secure
you need to take a few precautions. First of all redirect them to a strange URL so it can't be easily figured out. Pass the Facebook USER id. This is going to make sure that we are getting the right user from facebook. Then proceed to user that facebook user id to connect them to the database and match them with your User id. This adds a lot of extra security. User would HAVE to guess someones facebook ID in order to get access to the system. Then just do a standard login and redirect them back to your homepage (in logged in state.
Closing
There you go. I might enhance this later as I get more ideas. I tried to get all of my experiences out here as best I can. This was the first time I had setup facebook auth like this. It took me a total of 18 hours spread over 3-4 days to get this right. The main thing hanging me is I tried to use facebook_connect.php to handle one step, then facebook_connect2.php to handle the next step. Then I realized they had to be the exact same. That was something that I got hung up on the longest. Well good luck with your implementation, and I hoped that helped.
- Add new comment
- 878 reads