Authenticate Facebook Connect User

  1. Check Facebook Connect Cookies (example below)
    • 2c24418bf8fe35ce3e56bdb81510147e_expires = 1237932000
    • 2c24418bf8fe35ce3e56bdb81510147e_session_key = 3.giQwAnobPPDTc84_y7zuug__.86400.1237932000-705926010
    • 2c24418bf8fe35ce3e56bdb81510147e_ss = x0mM2T_o9B3YG7TfhLGoQQ__
    • 2c24418bf8fe35ce3e56bdb81510147e_user = 7059246010
    • 2c24418bf8fe35ce3e56bdb81510147e = 6aba0f0fc1f6c3fc0f2f477e9b0b0f93
  2. Remove APP_ID from front of all FB cookies
  3. Store FB user_id, session_key and Expected MD5 Hash.  MD5 Hash is the cookie without the extra stuff after the APP_ID (Last in list above)
  4. Strip APP_ID from all cookies and store as key=value in an array [“expires=1237932000”, “session_key=3.giQwAnobPPDTc84_y7zuug__.86400.1237932000-705926010″……etc]
  5. Sort array alphabetically (a,b,c,d…)
  6. Join array together into a string (“expires=1237932000session_key=3.giQwAnobPPDTc84_y7zu…….
  7. Append APP_SECRET to end of string
  8. MD5 Hash the resultant string from the above steps
  9. Compare the above MD5 hash with the Expected MD5 hash, if same, accept authentication.
  10. Lookup user from database with FB user_id
class Facebook

APP_ID = "XXXXXXXXXXXXXXXXXXXXXXXX"
APP_SECRET = "XXXXXXXXXXXXXXXXXXXXXX"

#http://wiki.developers.facebook.com/index.php/Verifying_The_Signature#Signatures_and_Facebook_Connect_Sites
def self.auth_fb_sig(cookies_string)
return nil if cookies_string.nil?

cookies_array = cookies_string.split(‘;’)

fb_sig = []
fb_expected_hash = nil
user_id = nil
user=nil
session_key = nil

cookies_array.each do |c|

if c.strip[0..APP_ID.size]==APP_ID+‘_’
keyvalue = c[APP_ID.size+2..c.size]
user_id = keyvalue[5..c.size] if keyvalue[0..3]==‘user’
session_key = keyvalue[12..c.size] if keyvalue[0..10]==‘session_key’
fb_sig << keyvalue
else
fb_expected_hash = c[APP_ID.size+2..c.size] if c.strip[0..APP_ID.size1]==APP_ID
end

end

return nil if fb_expected_hash.nil?

md5_hash=Digest::MD5.hexdigest(fb_sig.sort.join+APP_SECRET)

if(md5_hash==fb_expected_hash) #true if facebook user is verified
Facebook.log(user_id+" has been Facebook authenticated")
user = User.find_by_facebook_id(user_id)

if(user.nil?)
user = User.new
user.facebook_id = user_id
end
else
puts user_id+" has FAILED Facebook authentication" if user_id
end
user.session_key = session_key
user
end

Posted on March 24, 2009 at 9:48 am by Jordan Carter · Permalink
In: Uncategorized · Tagged with: , , ,

One Response

  1. Written by anony
    on July 14, 2011 at 3:11 pm
    Permalink

    you should implement an ip address check

Leave a Reply