Thursday, September 11, 2014

Facebook user authentication

On the client side, you can call the facebook api to login a user using their popup window. The user will get an very temporary (few hours) access-token which will be saved in a cookie (by the facebook api automatically) and can be used to create API calls.

In this post, we will discuss user-authentication which not quite the same. We want that our server will know that the user is legit.

How it worked before:

Signup: You had the signup with user&password pair (and usually an email for lost password...). The server will save this pair in the database.
Sign-in: Each time you attemp to login, you send the pair to the server and the server replay with good or bad.
Sign-in cookie: As you don`t want the user to re-login in every page, or every day, you can decide to put a cookie which bypass this. An (unscure) cookie can be the user&password, but in this case, if someone browse the cookies on the user-machine, he can see them. It can also be a temporary access-token, for example a unique number which is good for one-day and saved with the user/password pair. Tomorrow, it will be deleted and the user will have to relogin.

Facebook

Signup: The user already signed-up for facebook years ago. The user will have to permit your application to see his details, on the first login.
Sign-in: The user will see facebook login.
Sign-in cookie: facebook, behind-the-scenes, saves a temporary access-token so you will not have to, so if you call the user login again after a short time, the user will not see the login dialog.

The user code for using it is quite short, as facebook sdk is doing most of the work, and can be seen at facebook api login samples.


Combine the two: But how can my server know that the user is a legit one?

On the client side, if login was correct, we can send the server the facebook user-id and use it as a token.  This is only half-secure, as anyone with some programming skills, can get the facebook user id and modify our client code to impersonate someone else.
But, it will stop non-programmers/hackers , and can be used for prototyping ONLY stage.

A proper authentication is to send the server the facebook-id and the access-token (which is like user/password pair). The server will ask facebook to verify it (instead of looking into the local database) and then send a temporary cookie, which is the same as the user/password cookie. This will used so the user will not have to login again and again, and that our server will not have to verify the facebook-id/access-token.


And to the implementation

  1. Do it yourself means server code for asking facebook verification and a db table with facebook-user-id to session.
  2. On node.js you can use passport library to do part of the work for you.
  3. Using facebook parse clould-server framework, they will do all of it, including storing the db for you (but it is limiting as you won't have direct access)











No comments: