Facebook signature signature Invalid fill

I am trying to decrypt facebook signed_request in order to send the registration form to unauthorized users. My code is as follows:

def parse_signed_request(sr):

  encoded_sig, payload = sr.split('.', 2)
  data = json.loads(base64.b64decode( payload.replace('-_', '+/') ))

  if not data['algorithm'].upper() == 'HMAC-SHA256':
      raise ValueError('unknown algorithm {0}'.format(data['algorithm']))
      return None

  h = hmac.new(FB_APP_SECRET, digestmod=hashlib.sha256)
  h.update(payload)
  expected_sig = urlsafe_b64encode(h.digest()).replace('=', '')

  if encoded_sig != expected_sig:
    raise ValueError('bad signature')
    return None

return data

My problem is that, as in the case of this code, it works successfully for a user who has already registered, but for a user who is not logged in, I get an "Invalid filling" error for b64decode. However, if I fill the payload with the '=' signs, then all users pass the authorization as β€œlogged in”, regardless of whether they are valid.

Can anyone help me here?

+3
source share
1 answer

it works for me

def base64_url_decode(inp):
    inp = inp.replace('-','+').replace('_','/')
    padding_factor = (4 - len(inp) % 4) % 4
    inp += "="*padding_factor
    return base64.decodestring(inp)


def parse_signed_request(signed_request='a.a', secret=FACEBOOK_APP_SECRET):
    l = signed_request.split('.', 2)
    encoded_sig = l[0]
    payload = l[1]

    sig = base64_url_decode(encoded_sig)
    data = json.loads(base64_url_decode(payload))

    if data.get('algorithm').upper() != 'HMAC-SHA256':
        print('Unknown algorithm')
        return None
    else:
        expected_sig = hmac.new(secret, msg=payload, digestmod=hashlib.sha256).digest()

    if sig != expected_sig:
        return None
    else:
        print('valid signed request received..')
        return data
+6

All Articles