使用cookie密钥进行异步回调的身份验证

0 投票
1 回答
3113 浏览
提问于 2025-04-15 22:47

我需要写一个认证功能,这个功能要能从远程的认证API异步回调。简单的登录认证已经能正常工作,但用cookie密钥进行授权却不行。它应该检查cookie里是否有“lp_login”这个密钥,然后像异步操作一样获取API的地址,并执行on_response这个函数。

代码几乎能正常运行,但我发现了两个问题。首先,在on_response函数里,我需要在每个页面上为已授权的用户设置安全cookie。代码里的user_id能返回正确的ID,但这一行:self.set_secure_cookie("user", user_id)却不起作用。这可能是什么原因呢?

第二个问题是。在异步获取API地址的过程中,用户的页面在on_response设置“user”这个cookie之前就已经加载完成了,这样页面上会出现一个未授权的部分,里面有登录或注册的链接。这会让用户感到困惑。为了解决这个问题,我可以在用户尝试加载网站的首页时,停止页面的加载。这可能吗?如果可以的话,怎么做?也许这个问题还有其他更好的解决办法?

class BaseHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get_current_user(self):
        user_id = self.get_secure_cookie("user")
        user_cookie = self.get_cookie("lp_login")
        if user_id:
            self.set_secure_cookie("user", user_id)
            return Author.objects.get(id=int(user_id))
        elif user_cookie:
            url = urlparse("http://%s" % self.request.host)
            domain = url.netloc.split(":")[0]
            try:
                username, hashed_password = urllib.unquote(user_cookie).rsplit(',',1)
            except ValueError:
                # check against malicious clients
                return None
            else:
                url = "http://%s%s%s/%s/" % (domain, "/api/user/username/", username, hashed_password)
                http = tornado.httpclient.AsyncHTTPClient()
                http.fetch(url, callback=self.async_callback(self.on_response))
        else:
            return None

    def on_response(self, response):
        answer = tornado.escape.json_decode(response.body)
        username = answer['username']
        if answer["has_valid_credentials"]:
            author = Author.objects.get(email=answer["email"])
            user_id = str(author.id)
            print user_id # It returns needed id
            self.set_secure_cookie("user", user_id) # but session can's setup

1 个回答

3

看起来你在 Tornado 的邮件列表上也发了这个问题,可以在这里找到

你遇到的一个问题是,不能在 get_current_user 里面启动异步调用。你只能在 getpost 里面的某些操作中启动异步调用。

我没有测试过,但我觉得这个方法应该能让你接近你想要的结果。

#!/bin/python
import tornado.web
import tornado.http
import tornado.escape
import functools
import logging
import urllib

import Author

def upgrade_lp_login_cookie(method):
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        if not self.current_user and self.get_cookie('lp_login'):
            self.upgrade_lp_login(self.async_callback(method, self, *args, **kwargs))
        else:
            return method(self, *args, **kwargs)
    return wrapper


class BaseHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        user_id = self.get_secure_cookie("user")
        if user_id:
            return Author.objects.get(id=int(user_id))

    def upgrade_lp_login(self, callback):
        lp_login = self.get_cookie("lp_login")
        try:
            username, hashed_password = urllib.unquote(lp_login).rsplit(',',1)
        except ValueError:
            # check against malicious clients
            logging.info('invalid lp_login cookie %s' % lp_login)
            return callback()

        url = "http://%(host)s/api/user/username/%s/%s" % (self.request.host, 
                                                        urllib.quote(username), 
                                                        urllib.quote(hashed_password))
        http = tornado.httpclient.AsyncHTTPClient()
        http.fetch(url, self.async_callback(self.finish_upgrade_lp_login, callback))

    def finish_upgrade_lp_login(self, callback, response):
        answer = tornado.escape.json_decode(response.body)
        # username = answer['username']
        if answer['has_valid_credentials']:
            # set for self.current_user, overriding previous output of self.get_current_user()
            self._current_user = Author.objects.get(email=answer["email"])
            # set the cookie for next request
            self.set_secure_cookie("user", str(self.current_user.id))

        # now chain to the real get/post method
        callback()

    @upgrade_lp_login_cookie
    def get(self):
        self.render('template.tmpl')

撰写回答