Skip to content
Browse files

Base64 url encoding produces strings divisible by four, not by six

  • Loading branch information...
1 parent 64ebc17 commit 3e732653df77f98b9d70aa6a981e0f296481e6eb andy committed Aug 29, 2011
Showing with 5 additions and 20 deletions.
  1. +3 −15 lib/facebooker2/rails/controller.rb
  2. +2 −5 spec/rails/controller_spec.rb
View
18 lib/facebooker2/rails/controller.rb
@@ -36,7 +36,7 @@ def fetch_client_and_user
return if @_fb_user_fetched
# Try to authenticate from the signed request first
sig = fetch_client_and_user_from_signed_request
- sig = fetch_client_and_user_from_cookie if @_current_facebook_client.nil? and !signed_request_from_logged_out_user?
+ sig = fetch_client_and_user_from_cookie if @_current_facebook_client.nil?
#write the authentication params to a new cookie
if !@_current_facebook_client.nil?
@@ -226,32 +226,20 @@ def oauth2_fetch_client_and_user_from_cookie
return unless fb_cookie?
sig,payload = fb_cookie.split('.')
return unless oauth2_fb_cookie_signature_correct?(sig, payload)
- data = JSON.parse(oauth2_base64_url_decode(payload))
+ data = JSON.parse(fb_signed_request_json(payload))
authenticator = Mogli::Authenticator.new(Facebooker2.app_id, Facebooker2.secret, nil)
client = Mogli::Client.create_from_code_and_authenticator(data["code"], authenticator)
user = Mogli::User.new(:id=>data["user_id"])
fb_sign_in_user_and_client(user, client)
end
def oauth2_fb_cookie_signature_correct?(sig, payload)
- sig = oauth2_base64_url_decode(sig)
## From the PHP implementation
## https://developers.facebook.com/docs/authentication/signed_request/
-
+ sig = fb_signed_request_json(sig)
expected_signature = HMAC::SHA256.digest(Facebooker2.secret, payload)
return sig == expected_signature
end
-
- # Stolen from mini_fb.
- # Ruby's implementation of base64 decoding reads the string in multiples of 6 and ignores any extra bytes.
- # Since facebook does not take this into account, this function fills any string with white spaces up to
- # the point where it becomes divisible by 6, then it replaces '-' with '+' and '_' with '/' ( reverting the URL-safe encoding),
- # and decodes the result.
- def oauth2_base64_url_decode(str)
- str = str + "=" * (6 - str.size % 6) unless str.size % 6 == 0
- return Base64.decode64(str.tr("-_", "+/"))
- end
-
end
end
end
View
7 spec/rails/controller_spec.rb
@@ -206,15 +206,12 @@ class FakeController < ActionController::Base
end
end
- context "Using oauth2" do
+ describe "Using oauth2" do
let :controller do
controller = FakeController.new
end
- it "properly decodes base64 URL encoded string missing appropriate padding" do
- controller.oauth2_base64_url_decode('VGhpcyBpcyBlbmNvZGVkIQ').should == 'This is encoded!'
- end
- context "a valid signature" do
+ context "a FB cookie exists" do
before do
Facebooker2.secret='secret'
end

0 comments on commit 3e73265

Please sign in to comment.
Something went wrong with that request. Please try again.