Cookie
view release on metacpan or search on metacpan
# NAME
Cookie::Jar - Cookie Jar Class for Server & Client
# SYNOPSIS
use Cookie::Jar;
my $jar = Cookie::Jar->new( request => $r ) ||
die( "An error occurred while trying to get the cookie jar:", Cookie::Jar->error );
# set the default host
$jar->host( 'www.example.com' );
$jar->fetch;
# or using a HTTP::Request object
# Retrieve cookies from Cookie header sent from client
$jar->fetch( request => $http_request );
if( $jar->exists( 'my-cookie' ) )
{
# do something
}
# get the cookie
my $sid = $jar->get( 'my-cookie' );
# get all cookies
my @all = $jar->get( 'my-cookie', 'example.com', '/' );
# set a new Set-Cookie header
$jar->set( 'my-cookie' => $cookie_object );
# Remove cookie from jar
$jar->delete( 'my-cookie' );
# or using the object itself:
$jar->delete( $cookie_object );
# Create and add cookie to jar
$jar->add(
name => 'session',
value => 'lang=en-GB',
path => '/',
secure => 1,
same_site => 'Lax',
) || die( $jar->error );
# or add an existing cookie
$jar->add( $some_cookie_object );
my $c = $jar->make({
name => 'my-cookie',
domain => 'example.com',
value => 'sid1234567',
path => '/',
expires => '+10D',
# or alternatively
maxage => 864000
# to make it exclusively accessible by regular http request and not ajax
http_only => 1,
# should it be used under ssl only?
secure => 1,
});
# Add the Set-Cookie headers
$jar->add_response_header;
# Alternatively, using a HTTP::Response object or equivalent
$jar->add_response_header( $http_response );
$jar->delete( 'some_cookie' );
$jar->do(sub
{
# cookie object is available as $_ or as first argument in @_
});
# For client side
# Takes a HTTP::Response object or equivalent
# Extract cookies from Set-Cookie headers received from server
$jar->extract( $http_response );
# get by domain; by default sort it
my $all = $jar->get_by_domain( 'example.com' );
# Reverse sort
$all = $jar->get_by_domain( 'example.com', sort => 0 );
# Save cookies repository as json
$jar->save( '/some/where/mycookies.json' ) || die( $jar->error );
# Load cookies into jar
$jar->load( '/some/where/mycookies.json' ) || die( $jar->error );
# Save encrypted
$jar->save( '/some/where/mycookies.json',
{
encrypt => 1,
key => $key,
iv => $iv,
algo => 'AES',
}) || die( $jar->error );
# Load cookies from encrypted file
$jar->load( '/some/where/mycookies.json',
{
decrypt => 1,
key => $key,
iv => $iv,
algo => 'AES'
}) || die( $jar->error );
# Merge repository
$jar->merge( $jar2 ) || die( $jar->error );
# For autosave
my $jar = Cookie::Jar->new(
file => '/some/where/cookies.json',
# True by default
autosave => 1,
encrypt => 1,
secret => 'My big secret',
algo => 'AES',
) || die( Cookie::Jar->error );
say "There are ", $jar->length, " cookies in the repository.";
# Take a string from a Set-Cookie header and get a Cookie object
my $c = $jar->extract_one( $cookie_string );
# VERSION
v0.3.1
# DESCRIPTION
This is a module to handle [cookies](https://metacpan.org/pod/Cookie), according to the latest standard as set by [rfc6265](https://datatracker.ietf.org/doc/html/rfc6265), both by the http server and the client. Most modules out there are either anti...
For example, Apache2::Cookie does not work well in decoding cookies, and [Cookie::Baker](https://metacpan.org/pod/Cookie%3A%3ABaker) `Set-Cookie` timestamp format is wrong. They use Mon-09-Jan 2020 12:17:30 GMT where it should be, as per rfc 6265 Mon...
Also [APR::Request::Cookie](https://metacpan.org/pod/APR%3A%3ARequest%3A%3ACookie) and [Apache2::Cookie](https://metacpan.org/pod/Apache2%3A%3ACookie) which is a wrapper around [APR::Request::Cookie](https://metacpan.org/pod/APR%3A%3ARequest%3A%3ACoo...
This module supports modperl and uses a [Apache2::RequestRec](https://metacpan.org/pod/Apache2%3A%3ARequestRec) if provided, or can use package objects that implement similar interface as [HTTP::Request](https://metacpan.org/pod/HTTP%3A%3ARequest) an...
This module is also compatible with [LWP::UserAgent](https://metacpan.org/pod/LWP%3A%3AUserAgent), so you can use like this:
use LWP::UserAgent;
use Cookie::Jar;
my $ua = LWP::UserAgent->new(
cookie_jar => Cookie::Jar->new
);
It is also compatible with [HTTP::Promise](https://metacpan.org/pod/HTTP%3A%3APromise), such as:
use HTTP::Promise;
my $ua = HTTP::Promise->new( cookie_jar => Cookie::Jar->new );
This module does not die upon error, but instead returns `undef` and sets an [error](https://metacpan.org/pod/Module%3A%3AGeneric#error), so you should always check the return value of a method.
# METHODS
## new
This initiates the package and takes the following parameters:
- `request`
This is an optional parameter to provide a [Apache2::RequestRec](https://metacpan.org/pod/Apache2%3A%3ARequestRec) object. When provided, it will be used in various methods to get or set cookies from or onto http headers.
package MyApacheHandler;
use Apache2::Request ();
use Cookie::Jar;
sub handler : method
{
my( $class, $r ) = @_;
my $jar = Cookie::Jar->new( $r );
# Load cookies;
$jar->fetch;
$r->log_error( "$class: Found ", $jar->repo->length, " cookies." );
$jar->add(
name => 'session',
value => 'lang=en-GB',
path => '/',
secure => 1,
same_site => 'Lax',
);
# Will use Apache2::RequestRec object to set the Set-Cookie headers
$jar->add_response_header || do
{
$r->log_reason( "Unable to add Set-Cookie to response header: ", $jar->error );
return( Apache2::Const::HTTP_INTERNAL_SERVER_ERROR );
};
# Do some more computing
return( Apache2::Const::OK );
}
- `debug`
Optional. If set with a positive integer, this will activate verbose debugging message
## add
Provided with an hash or hash reference of cookie parameters (see [Cookie](https://metacpan.org/pod/Cookie)) and this will create a new [cookie](https://metacpan.org/pod/Cookie) and add it to the cookie repository.
Alternatively, you can also provide directly an existing [cookie object](https://metacpan.org/pod/Cookie)
my $c = $jar->add( $cookie_object ) || die( $jar->error );
## add\_cookie\_header
This is an alias for ["add\_request\_header"](#add_request_header) for backward compatibility with [HTTP::Cookies](https://metacpan.org/pod/HTTP%3A%3ACookies)
## add\_request\_header
Provided with a request object, such as, but not limited to [HTTP::Request](https://metacpan.org/pod/HTTP%3A%3ARequest) and this will add all relevant cookies in the repository into the `Cookie` http request header. The object method needs to have th...
As long as the object provided supports the `uri` and `header` method, you can provide any class of object you want.
Please refer to the [rfc6265](https://datatracker.ietf.org/doc/html/rfc6265) for more information on the applicable rule when adding cookies to the outgoing request header.
Basically, it will add, for a given domain, first all cookies whose path is longest and at path equivalent, the cookie creation date is used, with the earliest first. Cookies who have expired are not sent, and there can be cookies bearing the same na...
## add\_response\_header
# Adding cookie to the repository
$jar->add(
name => 'session',
value => 'lang=en-GB',
path => '/',
secure => 1,
same_site => 'Lax',
) || die( $jar->error );
# then placing it onto the response header
$jar->add_response_header;
This is the alter ego to ["add\_request\_header"](#add_request_header), in that it performs the equivalent function, but for the server side.
You can optionally provide, as unique argument, an object, such as but not limited to, [HTTP::Response](https://metacpan.org/pod/HTTP%3A%3AResponse), as long as that class supports the `header` method
Alternatively, if an [Apache object](https://metacpan.org/pod/Apache2%3A%3ARequestRec) has been set upon object instantiation or later using the ["request"](#request) method, then it will be used to set the outgoing `Set-Cookie` headers (there is one...
If no response, nor Apache2 object were set, then this will simply return a list of `Set-Cookie` in list context, or a string of possibly multiline `Set-Cookie` headers, or an empty string if there is no cookie found to be sent.
Be careful not to do the following:
# get cookies sent by the http client
$jar->fetch || die( $jar->error );
# set the response headers with the cookies from our repository
$jar->add_response_header;
Why? Well, because ["fetch"](#fetch) retrieves the cookies sent by the http client and store them into the repository. However, cookies sent by the http client only contain the cookie name and value, such as:
GET /my/path/ HTTP/1.1
Host: www.example.org
Cookie: session_token=eyJleHAiOjE2MzYwNzEwMzksImFsZyI6IkhTMjU2In0.eyJqdGkiOiJkMDg2Zjk0OS1mYWJmLTRiMzgtOTE1ZC1hMDJkNzM0Y2ZmNzAiLCJmaXJzdF9uYW1lIjoiSm9obiIsImlhdCI6MTYzNTk4NDYzOSwiYXpwIjoiNGQ0YWFiYWQtYmJiMy00ODgwLThlM2ItNTA0OWMwZTczNjBlIiwiaXNzIjoi...
As you can see, 3 cookies were sent: `session_token`, `csrf_token` and `site_prefs`
So, when ["fetch"](#fetch) creates an object for each one and store them, those cookies have no `path` value and no other attribute, and when ["add\_response\_header"](#add_response_header) is then called, it stringifies the cookies and create a `Set...
The http client, when receiving those cookies will derive the missing cookie path to be `/my/path`, i.e. the current uri path, and will create a duplicate cookie from the previously stored cookie with the same name for that host, but that had the pa...
So you can create a repository and use it to store the cookies sent by the http client using ["fetch"](#fetch), but in preparation of the server response, either use a separate repository with, for example, `my $jar_out = Cookie::Jar->new` or use ["s...
# Add Set-Cookie header for that cookie, but do not add cookie to repository
$jar->set( $cookie_object );
## algo
String. Sets or gets the algorithm to use when loading or saving the cookie jar.
## autosave
Boolean. Sets or gets the boolean value for automatically saving the cookie jar to the given file specified with ["file"](#file)
if( index( $path, $_->path ) == 0 )
{
return(1);
}
return(0);
});
print( "Found cookies: ", $found->map(sub{$_->name})->join( ',' ), "\n" );
## encrypt
Boolean. Sets or gets the boolean value for whether to encrypt or not the cookie jar when saving it, or whether to decrypt it when loading cookies from it.
This defaults to false.
## exists
Given a cookie name, this will check if it exists.
It returns 1 if it does, or 0 if it does not.
## extract
Provided with a response object, such as, but not limited to [HTTP::Response](https://metacpan.org/pod/HTTP%3A%3AResponse), and this will retrieve any cookie sent from the remote server, parse them and add their respective to the repository.
As per the [rfc6265, section 5.3.11 specifications](https://datatracker.ietf.org/doc/html/rfc6265#section-5.3) if there are duplicate cookies for the same domain and path, only the last one will be retained.
If the cookie received does not contain any `Domain` specification, then, in line with rfc6265 specifications, it will take the root of the current domain as the default domain value. Since finding out what is the root for a domain name is a non-triv...
## extract\_cookies
This is an alias for ["extract"](#extract) for backward compatibility with [HTTP::Cookies](https://metacpan.org/pod/HTTP%3A%3ACookies)
## extract\_one
This method takes a cookie string, which can be found in the `Set-Cookie` header, parse it, and returns a [Cookie](https://metacpan.org/pod/Cookie) object if successful, or sets an [error](https://metacpan.org/pod/Module%3A%3AGeneric#error) and retur...
It also takes an hash or hash reference of options.
The following options are supported:
- `host`
If provided, it will be used to find out the host's root domain, and to set the cookie object `domain` property if none is specified in the cookie string.
- `path`
If provided, it will be used to set the cookie object `path` property.
- `port`
If provided, it will be used to set the cookie object `port` property.
## fetch
This method does the equivalent of ["extract"](#extract), but for the server.
It retrieves all possible cookies from the http request received from the web browser.
It takes an optional hash or hash reference of parameters, such as `host`. If it is not provided, the value set with ["host"](#host) is used instead.
If the parameter `request` containing an http request object, such as, but not limited to [HTTP::Request](https://metacpan.org/pod/HTTP%3A%3ARequest), is provided, it will use it to get the `Cookie` header value. The object method needs to have the `...
Alternatively, if a value for ["request"](#request) has been set, it will use it to get the `Cookie` header value from Apache modperl.
You can also provide the `Cookie` string to parse by providing the `string` option to this method.
$jar->fetch( string => q{foo=bar; site_prefs=lang%3Den-GB} ) ||
die( $jar->error );
Ultimately, if none of those are available, it will use the environment variable `HTTP_COOKIE`
If the option `store` is true (by default it is true), this method will add the fetched cookies to the [repository](#repo).
It returns an hash reference of cookie key => [cookie object](https://metacpan.org/pod/Cookie)
A cookie key is made of the host (possibly empty), the path and the cookie name separated by `;`
# Cookies added to the repository
$jar->fetch || die( $jar->error );
# Cookies returned, but NOT added to the repository
my $cookies = $jar->fetch || die( $jar->error );
## file
Sets or gets the file path to the cookie jar file.
If provided upon instantiation, and if the file exists on the filesystem and is not empty, `Cookie::Jar` will load all the cookies from it.
If ["autosave"](#autosave) is set to a true, `Cookie::Jar` will automatically save all cookies to the specified cookie jar file, possibly encrypting it if ["algo"](#algo) and ["secret"](#secret) are set.
## get
Given a cookie name, an optional host and an optional path, this will retrieve its corresponding [cookie object](https://metacpan.org/pod/Cookie) and return it.
If not found, it will try to return a value with just the cookie name.
If nothing is found, this will return and empty list in list context or `undef` in scalar context.
You can `get` multiple cookie object and this method will return a list in list context and the first cookie object found in scalar context.
# Wrong, an undefined returned value here only means there is no such cookie
my $c = $jar->get( 'my-cookie' );
die( $jar->error ) if( !defined( $c ) );
# Correct
my $c = $jar->get( 'my-cookie' ) || die( "No cookie my-cookie found\n" );
# Possibly get multiple cookie object for the same name
my @cookies = $jar->get( 'my_same_name' ) || die( "No cookies my_same_name found\n" );
# or
my @cookies = $jar->get( 'my_same_name' => 'www.example.org', '/private' ) || die( "No cookies my_same_name found\n" );
## get\_by\_domain
Provided with a host and an optional hash or hash reference of parameters, and this returns an [array object](https://metacpan.org/pod/Module%3A%3AGeneric%3A%3AArray) of [cookie objects](https://metacpan.org/pod/Cookie) matching the domain specified.
If a `sort` parameter has been provided and its value is true, this will sort the cookies by path alphabetically. If the sort value exists, but is false, this will sort the cookies by path but in a reverse alphabetical order.
By default, the cookies are sorted.
## host
Sets or gets the default host. This is especially useful for cookies repository used on the server side.
( run in 1.017 second using v1.01-cache-2.11-cpan-98e64b0badf )