Plack::Middleware::Session管理的cookie如何设置过期时间?

How to set the expiration time for a cookie managed by Plack::Middleware::Session?

现在我的 app.psgi 包含(简化):

builder {
      enable 'Session', store => 'File'; #default uses Plack::Session::State::Cookie
      $app;
};

稍后,在 $app 我使用:

my $req = Plack::Request->new($env);
my $session = $req->session(); #returns env->{'psgix.session'}
$session->{user} = "name";

有效正常,例如:

现在,我想在我的登录面板中实现 "Remember me" 功能。在这种情况下,会话状态 cookie 不应从浏览器中自动删除。这可以通过使用 Plack::Session::State::Cookie.

中的 expires 方法来完成

问题:

如何从我的 $app 更改 cookie 过期时间(由 Session 中间件管理)。换句话说,如何在这里稍微调用expire方法:

my $req = Plack::Request->new($env);
my $session = $req->session(); #returns env->{'psgix.session'}
$session->{user} = "name";
my $cookie_state = WHAT_TO_DO_HERE_TO_GET; #the current Plack::Session::State::Cookie object
$cookie_state->expire(86400*14); #expire in two weeks

如果有人需要,这里有一个工作示例。

use strict;
use warnings;
use Plack::Request;
use Plack::Response;
use Plack::Builder;
use Data::Dumper;

my $app = sub {
    my $env = shift;
    my $req = Plack::Request->new($env);
    my $session = $req->session;
    my $res = Plack::Response->new(200);
    $res->content_type('text/html');
    my $link = $session->{user}
            ? q{ <a href="/logout">logout</a>}
            : q{ <a href="/login">login</a>}
            ;
    $res->body(["Session user:", $session->{user}, "<br>$link"]);
    return $res->finalize;
};

my $login = sub {
    my $env = shift;
    my $req = Plack::Request->new($env);
    my $session = $req->session;

    $session->{user} = "some";
    #how to set here the session-state-cookie expiration?

    my $res = Plack::Response->new();
    $res->redirect("/", 302);
    return $res->finalize;
};

my $logout = sub {
    my $env = shift;
    my $req = Plack::Request->new($env);
    my $session = $req->session;
    delete $session->{user};
    my $res = Plack::Response->new();
    $res->redirect("/", 302);
    return $res->finalize;
};

builder {
    enable 'Session', store => 'File';
    mount "/login" => $login; 
    mount "/logout" => $logout; 
    mount "/favicon.ico" => sub { return [ 404, ['Content-Type' => 'text/html'], [ '404 Not Found' ] ] };
    mount "/" => $app; 
};

您不能直接更改到期日期,但您可以强制会话中间件创建一个具有新到期日期的新会话,如下所示:

$env->{'psgix.session.options'}{change_id} = 1;
$env->{'psgix.session.options'}{expires}   = $my_expires;

如果用户登录,您应该将 ID 更改为 prevent session fixation attacks. See Cookie::Baker 以支持到期日期格式。

编辑:如果要全局设置默认过期超时,可以手动构建状态对象并将expires参数传递给构造函数:

builder {
    enable 'Session',
        state => Plack::Session::State->new(
            expires => $timeout_in_seconds,
        );
    $app;
};