.\" Automatically generated by Pod::Man 4.10 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Catalyst::Plugin::Session::Tutorial 3pm" .TH Catalyst::Plugin::Session::Tutorial 3pm "2018-12-22" "perl v5.28.1" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Catalyst::Plugin::Session::Tutorial \- Understanding and using sessions. .SH "ASSUMPTIONS" .IX Header "ASSUMPTIONS" This tutorial assumes that you are familiar with web applications in general and Catalyst specifically (up to models and configuration), and that you know what \s-1HTTP\s0 is. .SH "WHAT ARE SESSIONS" .IX Header "WHAT ARE SESSIONS" When users use a site, especially one that knows who they are (sites you log in to, sites which let you keep a shopping cart, etc.), the server preparing the content has to know that request X comes from client A while request Y comes from client B, so that each user gets the content meant for them. .PP The problem is that \s-1HTTP\s0 is a stateless protocol. This means that every request is distinct, and even if it comes from the same client, it's difficult to know that. .PP The way sessions are maintained between distinct requests is that the client says, for every request, \*(L"I'm client A\*(R" or \*(L"I'm client B\*(R". .PP This piece of data that tells the server \*(L"I'm X\*(R" is called the session \s-1ID,\s0 and the threading of several requests together is called a session. .SH "HOW SESSIONS WORK" .IX Header "HOW SESSIONS WORK" .SS "Cookies" .IX Subsection "Cookies" \&\s-1HTTP\s0 has a feature that lets this become easier, called cookies. A cookie is something the server asks the client to save somewhere, and resend every time a request is made. .PP The way they work is that the server sends the \f(CW\*(C`Set\-Cookie\*(C'\fR header, with a cookie name, a value, and some metadata (like when it expires, what paths it applies to, etc.). The client saves this. .PP Then, on every subsequent request the client will send a \f(CW\*(C`Cookie\*(C'\fR header, with the cookie name and value. .SS "Cookie Alternatives" .IX Subsection "Cookie Alternatives" Another way is to make sure that the session \s-1ID\s0 is repeated is to include it in every \s-1URI.\s0 .PP This can be as either a part of the path, or as a query parameter. .PP This technique has several issues which are discussed in \&\*(L"\s-1CAVEATS\*(R"\s0 in Catalyst::Plugin::Session::State::URI. .SS "Server-Side Behavior" .IX Subsection "Server-Side Behavior" When the server receives the session \s-1ID\s0 it can then look this key up in a database of some sort. For example the database can contain a shopping cart's contents, user preferences, etc. .SH "USING SESSIONS" .IX Header "USING SESSIONS" In Catalyst, the Catalyst::Plugin::Session plugin provides an \s-1API\s0 for convenient handling of session data. This \s-1API\s0 is based on the older, less flexible and less reliable Catalyst::Plugin::Session::FastMmap. .PP The plugin is modular, and requires backend plugins to be used. .SS "State Plugins" .IX Subsection "State Plugins" State plugins handle session \s-1ID\s0 persistence. For example Catalyst::Plugin::Session::State::Cookie creates a cookie with the session \&\s-1ID\s0 in it. .PP These plugins will automatically set \f(CW\*(C`$c\->sessionid\*(C'\fR at the beginning of the request, and automatically cause \f(CW\*(C`$c\->sessionid\*(C'\fR to be saved by the client at the end of the request. .SS "Store Plugins" .IX Subsection "Store Plugins" The backend into which session data is stored is provided by these plugins. For example, Catalyst::Plugin::Session::Store::DBI uses a database table to store session data, while Catalyst::Plugin::Session::Store::FastMmap uses Cache::FastMmap. .SS "Configuration" .IX Subsection "Configuration" First you need to load the appropriate plugins into your Catalyst application: .PP .Vb 1 \& package MyApp; \& \& use Catalyst qw/ \& Session \& Session::State::Cookie \& Session::Store::File \& /; .Ve .PP This loads the session \s-1API,\s0 as well as the required backends of your choice. .PP After the plugins are loaded they need to be configured. This is done according to \*(L"Configure_your_application\*(R" in Catalyst::Manual::Cookbook. .PP Each backend plugin requires its own configuration options (with most plugins providing sensible defaults). The session \s-1API\s0 itself also has configurable options listed in \*(L"\s-1CONFIGURATION\*(R"\s0 in Catalyst::Plugin::Session. .PP For the plugins above we don't need any configuration at all \- they should work out of the box, but suppose we did want to change some things around, it'll look like this: .PP .Vb 4 \& MyApp\->config( \*(AqPlugin::Session\*(Aq => { \& cookie_name => "my_fabulous_cookie", \& storage => "/path/to/store_data_file", \& }); .Ve .SS "Usage" .IX Subsection "Usage" Now, let's say we have an online shop, and the user is adding an item to the shopping cart. .PP Typically the item the user was viewing would have a form or link that adds the item to the cart. .PP Suppose this link goes to \f(CW\*(C`/cart/add/foo_baz/2\*(C'\fR, meaning that we want two units of the item \f(CW\*(C`foo_baz\*(C'\fR to be added to the cart. .PP Our \f(CW\*(C`add\*(C'\fR action should look something like this: .PP .Vb 1 \& package MyApp::Controller::Cart; \& \& sub add : Local { \& my ( $self, $c, $item_id, $quantity ) = @_; \& $quantity ||= 1; \& \& if ( $c\->model("Items")\->item_exists($item_id) ) { \& $c\->session\->{cart}{$item_id} += $quantity; \& } else { \& die "No such item"; \& } \& } .Ve .PP The way this works is that \f(CW\*(C`$c\->session\*(C'\fR always returns a hash reference to some data which is stored by the storage backend plugin. The hash reference returned always contains the same items that were in there at the end of the last request. .PP All the mishmash described above is done automatically. First, the method looks to see if a session \s-1ID\s0 is set. This session \s-1ID\s0 will be set by the State plugin if appropriate, at the start of the request (e.g. by looking at the cookies sent by the client). .PP If a session \s-1ID\s0 is set, the store will be asked to retrieve the session data for that specific session \s-1ID,\s0 and this is returned from \&\f(CW\*(C`$c\->session\*(C'\fR. This retrieval is cached, and will only happen once per request, if at all. .PP If a session \s-1ID\s0 is not set, a new one is generated, a new anonymous hash is created and saved in the store with the session \s-1ID\s0 as the key, and the reference to the hash is returned. .PP The action above takes this hash reference, and updates a nested hash within it, that counts quantity of each item as stored in the cart. .PP Any cart-listing code can then look into the session data and use it to display the correct items, which will, of course, be remembered across requests. .PP Here is an action some Template Toolkit example code that could be used to generate a cart listing: .PP .Vb 2 \& sub list_cart : Local { \& my ( $self, $c ) = @_; \& \& # get the cart data, that maps from item_id to quantity \& my $cart = $c\->session\->{cart} || {}; \& \& # this is our abstract model in which items are stored \& my $storage = $c\->model("Items"); \& \& # map from item_id to item (an object or hash reference) \& my %items = map { $_ => $storage\->get_item($_) } keys %$cart; \& \& # put the relevant info on the stash \& $c\->stash\->{cart}{items} = \e%items; \& $c\->stash\->{cart}{quantity} = $cart; \& } .Ve .PP And [a part of] the template it forwards to: .PP .Vb 1 \& \& \& \& \& \& \& \& \& \& \& \& \& [%# the table body lists all the items in the cart %] \& [% FOREACH item_id = cart.items.keys %] \& \& [%# each item has its own row in the table %] \& \& [% item = cart.items.$item_id %] \& [% quantity = cart.quantity.$item_id %] \& \& \& \& \& \& \& \& \& \& [% END %] \& \& \& \& \& \& \& \& \& \& \&
ItemQuantityPriceremove
\& [%# item.name is an attribute in the item \& # object, as loaded from the store %] \& [% item.name %] \& \& [%# supposedly this is part of a form where you \& # can update the quantity %] \& \& $ [% item.price * quantity %] \& \& \& \&
Total: \& [%# calculate sum in this cell \- too \& # much headache for a tutorial ;\-) %] \& \& Empty cart \&
.Ve .PP As you can see the way that items are added into \f(CW\*(C`$c\->session\->{cart}\*(C'\fR is pretty simple. Since \f(CW\*(C`$c\->session\*(C'\fR is restored as necessary, and contains data from previous requests by the same client, the cart can be updated as the user navigates the site pretty transparently. .SH "SECURITY ISSUES" .IX Header "SECURITY ISSUES" These issues all relate to how session data is managed, as described above. These are not issues you should be concerned about in your application code, but are here for their educational value. .SS "(Not) Trusting the Client" .IX Subsection "(Not) Trusting the Client" In order to avoid the overhead of server-side data storage, the session data can be included in the cookie itself. .PP There are two problems with this: .IP "1." 4 The user can change the data. .IP "2." 4 Cookies have a 4 kilobyte size limit. .Sp The size limit is of no concern in this section, but data changing is. In the database scheme the data can be trusted, since the user can neither read nor write it. However, if the data is delegated to the user, then special measures have to be added for ensuring data integrity, and perhaps secrecy too. .Sp This can be implemented by encrypting and signing the cookie data, but this is a big headache. .SS "Session Hijacking" .IX Subsection "Session Hijacking" What happens when client B says \*(L"I'm client A\*(R"? Well, basically, the server buys it. There's no real way around it. .PP The solution is to make \*(L"I'm client A\*(R" a difficult thing to say. This is why session IDs are randomized. If they are properly randomized, session IDs are so hard to guess that they must be stolen instead. .PP This is called session hijacking. There are several ways one might hijack another user's session. .PP \fICross Site Scripting\fR .IX Subsection "Cross Site Scripting" .PP One is by using cross site scripting attacks to steal the cookie data. In community sites, where users can cause the server to display arbitrary \s-1HTML,\s0 they can use this to put JavaScript code on the server. .PP If the server does not enforce a strict subset of tags that may be used, the malicious user could use this code to steal the cookies (there is a JavaScript \&\s-1API\s0 that lets cookies be accessed, but this code has to be run on the same website that the cookie came from). .PP \fISocial Engineering\fR .IX Subsection "Social Engineering" .PP By tricking a user into revealing a \s-1URI\s0 with session data embedded in it (when cookies are not used), the session \s-1ID\s0 can also be stolen. .PP Also, a naive user could be tricked into showing the cookie data from the browser to a malicious user. .SH "AUTHOR" .IX Header "AUTHOR" Yuval Kogman