python oauth 2.0新的fbsr facebook cookie,错误验证验证码

时间:2011-09-28 15:19:09

标签: python google-app-engine facebook-oauth

我正在尝试使用新的fbsr _ {{appID}} Cookie。

我正在使用以下函数来解析它,但是当我尝试获取access_token之后,我收到'错误验证验证码'消息。这些解析函数有问题吗?如果没有,那可能是什么问题?

更多信息: 我设法使用oauth链接在没有cookie的情况下登录用户,该链接以代码作为参数重定向回我的网站,因此它不能是app id,app secret或redirect_uri。另一个原因是它们有不同的错误信息。

def base64_url_decode(inp):
    padding_factor = (4 - len(inp) % 4) % 4
    inp += "="*padding_factor 
    return base64.b64decode(unicode(inp).translate(dict(zip(map(ord, u'-_'), u'+/'))))

def parse_signed_request(signed_request, 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':
        logging.error('Unknown algorithm')
        return None
    else:
        expected_sig = hmac.new(secret, msg=payload, digestmod=hashlib.sha256).digest()

    if sig != expected_sig:
        return None
    else:
        logging.debug('valid signed request received..')
        return data

args = {}
args['client_id'] = fbapp_id
args['redirect_uri'] = site_url 
args['client_secret'] = fbapp_secret
args['code'] = code
response = urllib.urlopen('https://graph.facebook.com/oauth/access_token?'+urllib.urlencode(args))
# ... here i'm getting the error back from the server: error validating verification code...

2 个答案:

答案 0 :(得分:10)

facebook python SDK的修改版本支持OAuth 2.0并在github上解析fbsr_ cookie:

https://gist.github.com/1190267

您可以查看代码以了解如何解析cookie或让该文件为您完成工作。

答案 1 :(得分:0)

为了退出工作,我必须以编程方式使cookie过期。来自facebook的链接不起作用,但是服务器端oauth可以在没有javascript的情况下注销:

class LogoutHandler(webapp2.RequestHandler):
    def get(self):
        self.set_cookie("fbsr_" + facebookconf.FACEBOOK_APP_ID, None, expires=time.time() - 86400)
        self.redirect("/")
    def set_cookie(self, name, value, expires=None):

        if value is None:
            value = 'deleted'
            expires = datetime.timedelta(minutes=-50000)
        jar = Cookie.SimpleCookie()
        jar[name] = value
        jar[name]['path'] = '/'
        if expires:
            if isinstance(expires, datetime.timedelta):
                expires = datetime.datetime.now() + expires
            if isinstance(expires, datetime.datetime):
                expires = expires.strftime('%a, %d %b %Y %H:%M:%S')
            jar[name]['expires'] = expires
        self.response.headers.add_header(*jar.output().split(': ', 1))

您能否更新您的问题,告诉我们它是如何进行以及我们如何处理Cookie。对于facebook-oath,你有注销工作吗?我不得不为此添加一个cookie处理和一个注销处理程序,但现在经过多次故障排除后,它可以工作。我这样登录:

class OAuthHandler(I18NHandler):
    def get(self):
      args = dict(
        code = self.request.get('code'),
        client_id = facebookconf.FACEBOOK_APP_ID,
        client_secret = facebookconf.FACEBOOK_APP_SECRET,
        redirect_uri = 'http://www.koolbusiness.com/oauth',
      )
      file = urllib.urlopen("https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args))
      try:
        token_response = file.read()
      finally:
        file.close()
      access_token = cgi.parse_qs(token_response)["access_token"][-1]
      graph = main.GraphAPI(access_token)
      user = graph.get_object("me")   
      self.response.out.write(user["id"])
      self.response.out.write(user["name"])


def get(self):
    fbuser=None
    profile = None
    access_token = None
    accessed_token = None
    if self.request.get('code'):
      args = dict(
        code = self.request.get('code'),
        client_id = facebookconf.FACEBOOK_APP_ID,
        client_secret = facebookconf.FACEBOOK_APP_SECRET,
        redirect_uri = 'http://'+self.get_host()+'/',
      )
      logging.debug("client_id"+str(args))
      file = urllib.urlopen("https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args))
      try:
        logging.debug("reading file")
        token_response = file.read()
        logging.debug("read file"+str(token_response))
      finally:
        file.close()
      access_token = cgi.parse_qs(token_response)["access_token"][-1]
      graph = main.GraphAPI(access_token)
      user = graph.get_object("me")   #write the access_token to the datastore
      fbuser = main.FBUser.get_by_key_name(user["id"])
      logging.debug("fbuser "+fbuser.name)

      if not fbuser:
        fbuser = main.FBUser(key_name=str(user["id"]),
                            id=str(user["id"]),
                            name=user["name"],
                            profile_url=user["link"],
                            access_token=access_token)
        fbuser.put()
      elif fbuser.access_token != access_token:
        fbuser.access_token = access_token
        fbuser.put()

    current_user = main.get_user_from_cookie(self.request.cookies, facebookconf.FACEBOOK_APP_ID, facebookconf.FACEBOOK_APP_SECRET)
    if current_user:
      graph = main.GraphAPI(current_user["access_token"])
      profile = graph.get_object("me")
      accessed_token = current_user["access_token"]