python - 如何在 Tornado 中设置 'secure' 和 'httponly' cookie?

标签 python cookies tornado

我有一个 Tornado 应用程序,它使用 Google Oauth 2.0 身份验证,获取电子邮件并将其设置在 cookie 中。现在我不希望任何其他人访问此 cookie、复制值并在我的应用程序上获取其他用户的详细信息。所以我想制作这个 cookie httponlysecure cookie。但是,当我将这些作为参数传递时,它无法设置 cookie:

self.set_secure_cookie('trakr', email, secure=True, httponly=True)

我起诉 Tornado 3.2.2 和 Python 2.7.5。

由于无法设置 cookie,它一直重定向到 google 授权页面。这是我的代码:

class GAuthLoginHandler(BaseHandler, tornado.auth.GoogleOAuth2Mixin):
    @tornado.gen.coroutine
    def get(self):
        if self.get_current_user():
            self.redirect('/products')
            return

        if self.get_argument('code', False):
            user = yield self.get_authenticated_user(redirect_uri=settings.google_redirect_url,
                code=self.get_argument('code'))
            if not user:
                self.clear_all_cookies() 
                raise tornado.web.HTTPError(500, 'Google authentication failed')

            access_token = str(user['access_token'])
            http_client = self.get_auth_http_client()
            response =  yield http_client.fetch('https://www.googleapis.com/oauth2/v1/userinfo?access_token='+access_token)
            user = json.loads(response.body)
            self.set_secure_cookie('trakr', user['email'], secure=True, httponly=True)
            self.redirect(self.get_argument("next", "/products"))
            return

        elif self.get_secure_cookie('trakr'):
            self.redirect('/products')
            return

        else:
            yield self.authorize_redirect(
                redirect_uri=settings.google_redirect_url,
                client_id=self.settings['google_oauth']['key'],
                scope=['email'],
                response_type='code',
                extra_params={'approval_prompt': 'auto'})

当我删除 securehttponly 参数时,代码工作得很好。如果我只发送 httponly 参数,它也可以工作,但是当我传递这两个参数时它似乎没有设置 cookie。

我做错了什么吗?

最佳答案

问题不在于 Tornado 或 Python,而在于我的服务器,因为我没有使用 HTTPS :

A secure cookie has the secure attribute enabled and is only used via HTTPS, ensuring that the cookie is always encrypted when transmitting from client to server. This makes the cookie less likely to be exposed to cookie theft via eavesdropping. In addition to that, all cookies are subject to browser's same-origin policy.

关于python - 如何在 Tornado 中设置 'secure' 和 'httponly' cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24668642/

相关文章:

Python请求,如何登录网站

Python SSL 套接字服务器

python - 在 Tornado 下运行 Pyramid WSGI 应用程序

Python:从数据库列查询干净的字符串值或清理 View /模板上的字符串是否更快?

python - DICOM 文件的医学图像质量问题

iphone - NSURLConnection,使用错误的凭据登录成功

cookies - 如何在 "laravel"中设置没有响应的cookie

python - 如何在 Tornado 中返回没有默认模板的 HTTP 错误代码?

python - 如何访问 optparse-add_action 的 nargs?

python - 从tfrecords导入数据时批处理后标签顺序错误