如何设置没有过期日期的 cookie 以及如何设置自定义 cookie 标头?

发布于 2024-12-24 15:59:38 字数 699 浏览 2 评论 0原文

默认情况下,cookie 在会话结束时过期,因此用户每次关闭浏览器后都需要登录。但是记住选项怎么样——如何设置没有过期日期的cookie?我尝试在development.ini 文件中添加 session.cookie_expires = False ,但没有帮助。

另一个问题:如何设置自定义 cookie 标头(例如将 lang 设置为没有过期日期的主 cookie)?

编辑:

我在 pyramid.authentication.AuthTktAuthenticationPolicy 允许您在之间保存 cookie会议。但是,当 max_age__init__.py (配置)文件中定义它时,如何实现 remember me 复选框并remember me必须在登录视图中定义?

By default, cookies expires at session end, so user need to login every time after closing the browser. But what about remember option - how to set cookie with no expiration date? I've tried to add session.cookie_expires = False in development.ini file, but it didn't help.

And another question: how to set custom cookie header (for example lang to main cookie with no expiration date too)?

EDIT:

I've found max_age parametr in pyramid.authentication.AuthTktAuthenticationPolicy which lets you save a cookie between sessions. But how to implement remember me checkbox when max_age defines it in __init__.py (config) file and remember me must be defined in login view?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

在风中等你 2024-12-31 15:59:39

这不是正确的方法,但有效。

def login_user(request, usesr_id, time=None):
"""
@type request: pyramid.request.Request
@type usesr_id: int
@type time: int 
@rtype: Response
"""
request.session["user_id"] = usesr_id
if time is not None:
    request.session._sess.cookie_expires = datetime.timedelta(seconds=time)
    request.session._sess._set_cookie_expires(None)
else:
    request.session._sess.cookie_expires = True
    request.session._sess._set_cookie_expires(None)
request.session._update_cookie_out()
request.session.save()

It's not correct way, but works.

def login_user(request, usesr_id, time=None):
"""
@type request: pyramid.request.Request
@type usesr_id: int
@type time: int 
@rtype: Response
"""
request.session["user_id"] = usesr_id
if time is not None:
    request.session._sess.cookie_expires = datetime.timedelta(seconds=time)
    request.session._sess._set_cookie_expires(None)
else:
    request.session._sess.cookie_expires = True
    request.session._sess._set_cookie_expires(None)
request.session._update_cookie_out()
request.session.save()
清眉祭 2024-12-31 15:59:39

我一直在寻找类似的解决方案。我使用 Bottle-cork.py 进行用户身份验证,并且需要一种方法来为用户提供“保持登录状态”选项。

from bottle, import request, response # etc...

def post_get(name, default=''):
    return bottle.request.POST.get(name, default).strip()

def login():
    """Authenticate users"""
    username = post_get('username').lower()
    password = post_get('password')
    keep_login = post_get('keep_login')
    session = request.environ['beaker.session']
    if keep_login == 'true':
        session.cookie_expires = False
        response.set_cookie('keep_login', "true")
    else:
        session.cookie_expires = True
        response.set_cookie('keep_login', "false")
    aaa.login(username, password)

但是,每次向服务器发送请求时,bottle 都会返回一个新的会话 cookie,默认返回到浏览器关闭时过期。为了解决这个问题,我添加了一个函数,每次发送请求时都会调用该函数:

def preserve_cookie(request):
    keep_login = request.get_cookie('keep_login')
    session = request.environ['beaker.session']
    if keep_login == 'true':
        session.cookie_expires = False
    return request

例如:

@bottle.get('/get_username')
def check_login(user=None):
    try:
        aaa.require(username=user)
    except:
        raise bottle.HTTPError(401)
    preserve_cookie(request)
    return aaa.current_user.username

这样,返回的新 cookie 就可以保持用户保存登录会话的偏好。然而,beaker.SessionMiddleware 目前的实现方式只是将 cookie 设置为 2038 年 1 月 18 日过期。

I was looking for a similar solution. I'm using bottle-cork.py for my user authentication and needed a way to give users the option "Keep me logged in"

from bottle, import request, response # etc...

def post_get(name, default=''):
    return bottle.request.POST.get(name, default).strip()

def login():
    """Authenticate users"""
    username = post_get('username').lower()
    password = post_get('password')
    keep_login = post_get('keep_login')
    session = request.environ['beaker.session']
    if keep_login == 'true':
        session.cookie_expires = False
        response.set_cookie('keep_login', "true")
    else:
        session.cookie_expires = True
        response.set_cookie('keep_login', "false")
    aaa.login(username, password)

However, every time a request is sent to the server, bottle returns a new session cookie that defaults back to expiring when the browser closes. To fix this, I added a function that I call every time a request is sent:

def preserve_cookie(request):
    keep_login = request.get_cookie('keep_login')
    session = request.environ['beaker.session']
    if keep_login == 'true':
        session.cookie_expires = False
    return request

So, for instance:

@bottle.get('/get_username')
def check_login(user=None):
    try:
        aaa.require(username=user)
    except:
        raise bottle.HTTPError(401)
    preserve_cookie(request)
    return aaa.current_user.username

This way the new cookie that is returned maintains the user's preference of keeping the login session saved. However, the way beaker.SessionMiddleware is currently implemented, it just sets the cookie to expire Jan 18, 2038.

征棹 2024-12-31 15:59:38

“记住我”背后的想法是,它是一个在登录和会话之间持续的选项。最好将其实现为单独的 cookie,如果用户选中该框,您就可以设置该 cookie。如果“记住我”意味着应用程序应该在策略过期时让您重新登录,那么只需存储一个永不过期的签名 cookie 即可。然后,当应用程序因用户未登录而引发 HTTPForbidden 时,您可以检查 cookie,了解他们想要被记住的情况,重新登录他们,并将他们重定向回他们所在的位置正想走。这只是一种选择,具体取决于您所说的“记住我”的含义。

配置 Pyramid 的默认会话工厂

如果您使用 UnencryptedCookieSessionFactoryConfig 会话工厂,则需要为 cookie_max_age 参数传递适当的值。还检查超时参数,它是存储在 cookie 中的签名时间戳。与 max_age 结合,会话的实际过期时间将是 max_age 和 timeout 中的最小值。

http://docs.pylonsproject .org/projects/pyramid/en/1.3-branch/api/session.html#pyramid.session.UnencryptedCookieSessionFactoryConfig

创建自定义 Cookie

要设置自定义 Cookie,您只需使用所需的参数调用 response.set_cookie() 即可。如果您使用渲染器,那么您可以通过 request.response 访问使用的响应对象。否则,如果您自己手动创建响应对象,只需将其设置在那里即可。

http://docs .pylonsproject.org/projects/pyramid/en/1.3-branch/api/response.html#pyramid.response.Response.set_cookie

The idea behind "remember me" is that it's an option that lasts between logins and sessions. This is best implemented as a separate cookie that you can set if the user checks the box. If "remember me" means that the application should log you back in if the policy has expired, then simply store a signed cookie that never expires. Then when the application raises an HTTPForbidden because the user isn't logged in, you can check for the cookie, see that they wanted to be remembered, log them back in, and redirect them back to where they were trying to go. That's just one option, depending on what you mean by "remember me".

Configuring Pyramid's Default Session Factory

If you are using the UnencryptedCookieSessionFactoryConfig session factory, then you need to pass an appropriate value for the cookie_max_age argument. The timeout parameter is also checked, which is a signed timestamp stored within the cookie. Combined with max_age, the actual expiration time of the session would be the minimum of max_age and timeout.

http://docs.pylonsproject.org/projects/pyramid/en/1.3-branch/api/session.html#pyramid.session.UnencryptedCookieSessionFactoryConfig

Creating Custom Cookies

To set a custom cookie you simply need to call response.set_cookie() with the parameters you'd like. If you are using a renderer then you can access the response object that's used via request.response. Otherwise if you are manually creating a response object yourself, just set it there.

http://docs.pylonsproject.org/projects/pyramid/en/1.3-branch/api/response.html#pyramid.response.Response.set_cookie

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文