Ωmega
Ωmega

Reputation: 43683

How to force CGI to double-quote cookie value

For a simple demonstration, let's use the following Perl code:

use strict;
use warnings;

use CGI qw /:standard/;
use MIME::Base64;

# ...

my $cookie = cookie( -name    => 'token',
                     -value   => '"' . encode_base64($token, '') . '"',
                     -expires => '+1y',
                   );

print header( -status    => 302,
              'Location' => $uri,
              -cookie    => $cookie,
            );

This script results in the following HTTP header:

enter image description here


However, I expected

Set-Cookie: token="lrv5Jy5KhkXb8qIWpgd3bA=="; path=/; expires=...


What should I do to get the desired cookie format?

Upvotes: 1

Views: 87

Answers (2)

Ωmega
Ωmega

Reputation: 43683

Solution #1:

print header( 
  -status      => 302,
  'Location'   => $uri,
  'Set-Cookie' => 'token="' . encode_base64($token, '') . '"; ' .
                  'path=/; expires=' . (POSIX::strftime 
                  "%a, %d-%b-%Y %T GMT", gmtime (time + 365*24*60*60)) # +1y
            );

Solution #2:

my $cookie = cookie( -name    => 'token',
                     -value   => '',
                     -expires => '+1y',
                   )
                   =~ s/=;/{ '="' . encode_base64($token, '') . '";' }/er;

print header( -status    => 302,
              'Location' => $uri,
              -cookie    => $cookie,
            );

Upvotes: 2

Quentin
Quentin

Reputation: 944175

Quotes around the cookie value are optional. The CGI module's authors choose not to include quotes, nor provide an API option to turn them on.

Your attempt is trying to include the quotes are part of the value instead of as characters that delimit it.

If you want to include the optional quotes, then you'll need to reimplement the cookie sub.

Upvotes: 3

Related Questions