perl – 如何设置由Plack :: Middleware :: Session管理的cookie的到期时间?

前端之家收集整理的这篇文章主要介绍了perl – 如何设置由Plack :: Middleware :: Session管理的cookie的到期时间?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
现在我的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";

它工作正常,例如:

>当用户登录时,我将他的名字存储在服​​务器端存储的会话文件中,而Plack::Middleware::Session设置了一个简单的会话状态cookie,
>当用户关闭浏览器时,cookie会自动清除(因为Plack::Session::State::Cookie默认情况下没有为cookie设置任何过期).

现在,我希望在登录面板中实现“记住我”功能.在这种情况下,不应从浏览器中自动删除sesion-state-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.有关支持的到期日期格式,请参阅Cookie::Baker.

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

builder {
    enable 'Session',state => Plack::Session::State->new(
            expires => $timeout_in_seconds,);
    $app;
};
原文链接:https://www.f2er.com/Perl/171810.html

猜你在找的Perl相关文章