简体   繁体   English

Perl Dancer会话Cookie

[英]Perl Dancer Session Cookies

I am just starting out with Dancer::Session::Cookie, and I have run into some behavior that I am not expecting. 我刚刚开始使用Dancer :: Session :: Cookie,我遇到了一些我不期待的行为。 I put together a simple Perl Dancer app to authenticate using Authen::Simple::ActiveDirectory. 我整理了一个简单的Perl Dancer应用程序,使用Authen :: Simple :: ActiveDirectory进行身份验证。 My routes are below. 我的路线在下面。

package auth;
use Dancer ':syntax';

our $VERSION = '0.1';

get '/' => sub {
    template 'index', {user => session->{user}};
};

hook 'before' => sub {
    if (! session('user') && request->path_info !~ m{^/login}) {
        var requested_path => request->path_info;
        request->path_info('/login');
    }
};

get '/login' => sub {
    # Display a login page; the original URL they requested is available as
    # vars->{requested_path}, so could be put in a hidden field in the form
    template 'login', { path => vars->{requested_path} };
};

post '/login' => sub {
    # Validate the username and password they supplied
    my $ad = Authen::Simple::ActiveDirectory->new( 
        host      => 'host',
        principal => 'example.com'
    );

    if ($ad->authenticate( params->{user}, params->{pass} )) {
        session user => params->{user};
        redirect params->{path} || '/';
    } else {
        redirect '/login?failed=1';
    }
};

get '/logout' => sub {
    session->destroy;
    redirect '/';
};

true;

I am able to successfully log in and create a session. 我能够成功登录并创建会话。 My username is placed on the main page after login, and I have a link to the /logout route. 我的用户名在登录后放在主页面上,我有一个指向/ logout路由的链接。 When I click on that link, the route is executed (I confirmed this in the debugger), but I am returned to the main page with my username still displayed. 当我点击该链接时,路由被执行(我在调试器中确认了这一点),但是我仍然显示我的用户名返回到主页面。 I would expect to be returned to the login page since no session exists. 由于不存在会话,我希望返回登录页面。 Any ideas why Dancer is behaving this way? 有没有想过为什么Dancer会这样做? Have I misunderstood how sessions work? 我误解了会话的运作方式吗?

I haven't used Dancer::Session::Cookie before, but it looks like the destroy method isn't right - it's just deleting the cookie entry from the parsed hash on the server end, but that doesn't ever get communicated back to the browser. 我之前没有使用过Dancer :: Session :: Cookie,但看起来像destroy方法不对 - 它只是从服务器端的解析哈希中删除了cookie条目,但是这种方法并没有得到回传到浏览器。

In place of the call to session->destroy try this: 代替对session->destroy的调用试试这个:

cookie session->session_name => '', expires => '-1 day';

That's the belt-and-suspenders approach - it empties the cookie and sets the expiration time to occur in the past. 这就是腰带和吊带的方法 - 它会清空cookie并设置过去发生的过期时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM