1Catalyst::Plugin::SessiUosne(r3)Contributed Perl DocumenCtaattailoynst::Plugin::Session(3)
2
3
4
6 Catalyst::Plugin::Session - Generic Session plugin - ties together
7 server side storage and client side state required to maintain session
8 data.
9
11 # To get sessions to "just work", all you need to do is use these plugins:
12
13 use Catalyst qw/
14 Session
15 Session::Store::FastMmap
16 Session::State::Cookie
17 /;
18
19 # you can replace Store::FastMmap with Store::File - both have sensible
20 # default configurations (see their docs for details)
21
22 # more complicated backends are available for other scenarios (DBI storage,
23 # etc)
24
25
26 # after you've loaded the plugins you can save session data
27 # For example, if you are writing a shopping cart, it could be implemented
28 # like this:
29
30 sub add_item : Local {
31 my ( $self, $c ) = @_;
32
33 my $item_id = $c->req->param("item");
34
35 # $c->session is a hash ref, a bit like $c->stash
36 # the difference is that it' preserved across requests
37
38 push @{ $c->session->{items} }, $item_id;
39
40 $c->forward("MyView");
41 }
42
43 sub display_items : Local {
44 my ( $self, $c ) = @_;
45
46 # values in $c->session are restored
47 $c->stash->{items_to_display} =
48 [ map { MyModel->retrieve($_) } @{ $c->session->{items} } ];
49
50 $c->forward("MyView");
51 }
52
54 The Session plugin is the base of two related parts of functionality
55 required for session management in web applications.
56
57 The first part, the State, is getting the browser to repeat back a
58 session key, so that the web application can identify the client and
59 logically string several requests together into a session.
60
61 The second part, the Store, deals with the actual storage of
62 information about the client. This data is stored so that the it may be
63 revived for every request made by the same client.
64
65 This plugin links the two pieces together.
66
68 Session::State::Cookie
69 The only really sane way to do state is using cookies.
70
71 Session::Store::File
72 A portable backend, based on Cache::File.
73
74 Session::Store::FastMmap
75 A fast and flexible backend, based on Cache::FastMmap.
76
78 sessionid
79 An accessor for the session ID value.
80
81 session
82 Returns a hash reference that might contain unserialized values
83 from previous requests in the same session, and whose modified
84 value will be saved for future requests.
85
86 This method will automatically create a new session and session ID
87 if none exists.
88
89 You can also set session keys by passing a list of key/value pairs
90 or a hashref.
91
92 $c->session->{foo} = "bar"; # This works.
93 $c->session(one => 1, two => 2); # And this.
94 $c->session({ answer => 42 }); # And this.
95
96 session_expires
97 This method returns the time when the current session will expire,
98 or 0 if there is no current session. If there is a session and it
99 already expired, it will delete the session and return 0 as well.
100
101 flash
102 This is like Ruby on Rails' flash data structure. Think of it as a
103 stash that lasts for longer than one request, letting you redirect
104 instead of forward.
105
106 The flash data will be cleaned up only on requests on which
107 actually use $c->flash (thus allowing multiple redirections), and
108 the policy is to delete all the keys which haven't changed since
109 the flash data was loaded at the end of every request.
110
111 Note that use of the flash is an easy way to get data across
112 requests, but it's also strongly disrecommended, due it it being
113 inherently plagued with race conditions. This means that it's
114 unlikely to work well if your users have multiple tabs open at
115 once, or if your site does a lot of AJAX requests.
116
117 Catalyst::Plugin::StatusMessage is the recommended alternative
118 solution, as this doesn't suffer from these issues.
119
120 sub moose : Local {
121 my ( $self, $c ) = @_;
122
123 $c->flash->{beans} = 10;
124 $c->response->redirect( $c->uri_for("foo") );
125 }
126
127 sub foo : Local {
128 my ( $self, $c ) = @_;
129
130 my $value = $c->flash->{beans};
131
132 # ...
133
134 $c->response->redirect( $c->uri_for("bar") );
135 }
136
137 sub bar : Local {
138 my ( $self, $c ) = @_;
139
140 if ( exists $c->flash->{beans} ) { # false
141
142 }
143 }
144
145 clear_flash
146 Zap all the keys in the flash regardless of their current state.
147
148 keep_flash @keys
149 If you want to keep a flash key for the next request too, even if
150 it hasn't changed, call "keep_flash" and pass in the keys as
151 arguments.
152
153 delete_session REASON
154 This method is used to invalidate a session. It takes an optional
155 parameter which will be saved in "session_delete_reason" if
156 provided.
157
158 NOTE: This method will also delete your flash data.
159
160 session_delete_reason
161 This accessor contains a string with the reason a session was
162 deleted. Possible values include:
163
164 • "address mismatch"
165
166 • "session expired"
167
168 session_expire_key $key, $ttl
169 Mark a key to expire at a certain time (only useful when shorter
170 than the expiry time for the whole session).
171
172 For example:
173
174 __PACKAGE__->config('Plugin::Session' => { expires => 10000000000 }); # "forever"
175 (NB If this number is too large, Y2K38 breakage could result.)
176
177 # later
178
179 $c->session_expire_key( __user => 3600 );
180
181 Will make the session data survive, but the user will still be
182 logged out after an hour.
183
184 Note that these values are not auto extended.
185
186 change_session_id
187 By calling this method you can force a session id change while
188 keeping all session data. This method might come handy when you are
189 paranoid about some advanced variations of session fixation attack.
190
191 If you want to prevent this session fixation scenario:
192
193 0) let us have WebApp with anonymous and authenticated parts
194 1) a hacker goes to vulnerable WebApp and gets a real sessionid,
195 just by browsing anonymous part of WebApp
196 2) the hacker inserts (somehow) this values into a cookie in victim's browser
197 3) after the victim logs into WebApp the hacker can enter his/her session
198
199 you should call change_session_id in your login controller like
200 this:
201
202 if ($c->authenticate( { username => $user, password => $pass } )) {
203 # login OK
204 $c->change_session_id;
205 ...
206 } else {
207 # login FAILED
208 ...
209 }
210
211 change_session_expires $expires
212 You can change the session expiration time for this session;
213
214 $c->change_session_expires( 4000 );
215
216 Note that this only works to set the session longer than the config
217 setting.
218
220 setup
221 This method is extended to also make calls to
222 "check_session_plugin_requirements" and "setup_session".
223
224 check_session_plugin_requirements
225 This method ensures that a State and a Store plugin are also in use
226 by the application.
227
228 setup_session
229 This method populates "$c->config('Plugin::Session')" with the
230 default values listed in "CONFIGURATION".
231
232 prepare_action
233 This method is extended.
234
235 Its only effect is if the (off by default) "flash_to_stash"
236 configuration parameter is on - then it will copy the contents of
237 the flash to the stash at prepare time.
238
239 finalize_headers
240 This method is extended and will extend the expiry time before
241 sending the response.
242
243 finalize_body
244 This method is extended and will call finalize_session before the
245 other finalize_body methods run. Here we persist the session data
246 if a session exists.
247
248 initialize_session_data
249 This method will initialize the internal structure of the session,
250 and is called by the "session" method if appropriate.
251
252 create_session_id
253 Creates a new session ID using "generate_session_id" if there is no
254 session ID yet.
255
256 validate_session_id SID
257 Make sure a session ID is of the right format.
258
259 This currently ensures that the session ID string is any amount of
260 case insensitive hexadecimal characters.
261
262 generate_session_id
263 This method will return a string that can be used as a session ID.
264 It is supposed to be a reasonably random string with enough bits to
265 prevent collision. It basically takes "session_hash_seed" and
266 hashes it using SHA-1, MD5 or SHA-256, depending on the
267 availability of these modules.
268
269 session_hash_seed
270 This method is actually rather internal to generate_session_id, but
271 should be overridable in case you want to provide more random data.
272
273 Currently it returns a concatenated string which contains:
274
275 • A counter
276
277 • The current time
278
279 • One value from "rand".
280
281 • The stringified value of a newly allocated hash reference
282
283 • The stringified value of the Catalyst context object
284
285 in the hopes that those combined values are entropic enough for
286 most uses. If this is not the case you can replace
287 "session_hash_seed" with e.g.
288
289 sub session_hash_seed {
290 open my $fh, "<", "/dev/random";
291 read $fh, my $bytes, 20;
292 close $fh;
293 return $bytes;
294 }
295
296 Or even more directly, replace "generate_session_id":
297
298 sub generate_session_id {
299 open my $fh, "<", "/dev/random";
300 read $fh, my $bytes, 20;
301 close $fh;
302 return unpack("H*", $bytes);
303 }
304
305 Also have a look at Crypt::Random and the various openssl bindings
306 - these modules provide APIs for cryptographically secure random
307 data.
308
309 finalize_session
310 Clean up the session during "finalize".
311
312 This clears the various accessors after saving to the store.
313
314 dump_these
315 See "dump_these" in Catalyst - ammends the session data structure
316 to the list of dumped objects if session ID is defined.
317
318 calculate_extended_session_expires
319 calculate_initial_session_expires
320 create_session_id_if_needed
321 delete_session_id
322 extend_session_expires
323 Note: this is *not* used to give an individual user a longer
324 session. See 'change_session_expires'.
325
326 extend_session_id
327 get_session_id
328 reset_session_expires
329 session_is_valid
330 set_session_id
331 initial_session_expires
332
334 The earliest point in time at which you may use the session data is
335 after Catalyst::Plugin::Session's "prepare_action" has finished.
336
337 State plugins must set $c->session ID before "prepare_action", and
338 during "prepare_action" Catalyst::Plugin::Session will actually load
339 the data from the store.
340
341 sub prepare_action {
342 my $c = shift;
343
344 # don't touch $c->session yet!
345
346 $c->NEXT::prepare_action( @_ );
347
348 $c->session; # this is OK
349 $c->sessionid; # this is also OK
350 }
351
353 $c->config('Plugin::Session' => {
354 expires => 1234,
355 });
356
357 All configuation parameters are provided in a hash reference under the
358 "Plugin::Session" key in the configuration hash.
359
360 expires
361 The time-to-live of each session, expressed in seconds. Defaults to
362 7200 (two hours).
363
364 expiry_threshold
365 Only update the session expiry time if it would otherwise expire
366 within this many seconds from now.
367
368 The purpose of this is to keep the session store from being updated
369 when nothing else in the session is updated.
370
371 Defaults to 0 (in which case, the expiration will always be
372 updated).
373
374 verify_address
375 When true, "$c->request->address" will be checked at prepare time.
376 If it is not the same as the address that initiated the session,
377 the session is deleted.
378
379 Defaults to false.
380
381 verify_user_agent
382 When true, "$c->request->user_agent" will be checked at prepare
383 time. If it is not the same as the user agent that initiated the
384 session, the session is deleted.
385
386 Defaults to false.
387
388 flash_to_stash
389 This option makes it easier to have actions behave the same whether
390 they were forwarded to or redirected to. On prepare time it copies
391 the contents of "flash" (if any) to the stash.
392
394 The hash reference returned by "$c->session" contains several keys
395 which are automatically set:
396
397 __expires
398 This key no longer exists. Use "session_expires" instead.
399
400 __updated
401 The last time a session was saved to the store.
402
403 __created
404 The time when the session was first created.
405
406 __address
407 The value of "$c->request->address" at the time the session was
408 created. This value is only populated if "verify_address" is true
409 in the configuration.
410
411 __user_agent
412 The value of "$c->request->user_agent" at the time the session was
413 created. This value is only populated if "verify_user_agent" is
414 true in the configuration.
415
417 Round the Robin Proxies
418 "verify_address" could make your site inaccessible to users who are
419 behind load balanced proxies. Some ISPs may give a different IP to each
420 request by the same client due to this type of proxying. If addresses
421 are verified these users' sessions cannot persist.
422
423 To let these users access your site you can either disable address
424 verification as a whole, or provide a checkbox in the login dialog that
425 tells the server that it's OK for the address of the client to change.
426 When the server sees that this box is checked it should delete the
427 "__address" special key from the session hash when the hash is first
428 created.
429
430 Race Conditions
431 In this day and age where cleaning detergents and Dutch football (not
432 the American kind) teams roam the plains in great numbers, requests may
433 happen simultaneously. This means that there is some risk of session
434 data being overwritten, like this:
435
436 1. request a starts, request b starts, with the same session ID
437
438 2. session data is loaded in request a
439
440 3. session data is loaded in request b
441
442 4. session data is changed in request a
443
444 5. request a finishes, session data is updated and written to store
445
446 6. request b finishes, session data is updated and written to store,
447 overwriting changes by request a
448
449 For applications where any given user's session is only making one
450 request at a time this plugin should be safe enough.
451
453 Andy Grundman
454
455 Christian Hansen
456
457 Yuval Kogman, "nothingmuch@woobling.org"
458
459 Sebastian Riedel
460
461 Tomas Doran (t0m) "bobtfish@bobtfish.net" (current maintainer)
462
463 Sergio Salvi
464
465 kmx "kmx@volny.cz"
466
467 Florian Ragwitz (rafl) "rafl@debian.org"
468
469 Kent Fredric (kentnl)
470
471 And countless other contributers from #catalyst. Thanks guys!
472
474 Devin Austin (dhoss) <dhoss@cpan.org>
475
476 Robert Rothenberg <rrwo@cpan.org> (on behalf of Foxtons Ltd.)
477
479 Copyright (c) 2005 the aforementioned authors. All rights
480 reserved. This program is free software; you can redistribute
481 it and/or modify it under the same terms as Perl itself.
482
483
484
485perl v5.38.0 2023-07-20 Catalyst::Plugin::Session(3)