Apache...Cookie(3pm)
π Apache...Cookie(3pm) π
User Contributed Perl Documentation β okay bestie, this is the manual page for Apache...Cookie(3pm), and we're about to make auth actually make sense. π
β¨ NAME β¨
Apache::AuthCookie β Perl Authentication and Authorization via cookies. πͺ
πΈ VERSION πΈ
version 3.32 β yes, that's the version, bestie. no cap.
π¦ SYNOPSIS π¦
First thing first: make sure your mod_perl is at least 1.24, with StackedHandlers, MethodHandlers, Authen, and Authz compiled in. That's the vibe check. β
Then you drop something like this into your config:
# In httpd.conf or .htaccess:
PerlModule Sample::Apache::AuthCookieHandler
PerlSetVar WhatEverPath /
PerlSetVar WhatEverLoginScript /login.pl
# use to alter how "require" directives are matched. Can be "Any" or "All".
# If its "Any", then you must only match Any of the "require" directives. If
# its "All", then you must match All of the require directives.
#
# Default: All
PerlSetVar WhatEverSatisfy Any
# The following line is optional - it allows you to set the domain
# scope of your cookie. Default is the current domain.
PerlSetVar WhatEverDomain .yourdomain.com
# Use this to only send over a secure connection
PerlSetVar WhatEverSecure 1
# Use this if you want user session cookies to expire if the user
# doesn't request a auth-required or recognize_user page for some
# time period. If set, a new cookie (with updated expire time)
# is set on every request.
PerlSetVar WhatEverSessionTimeout +30m
# to enable the HttpOnly cookie property, use HttpOnly.
# this is an MS extension. See
# http://msdn.microsoft.com/workshop/author/dhtml/httponly_cookies.asp
PerlSetVar WhatEverHttpOnly 1
# Usually documents are uncached - turn off here
PerlSetVar WhatEverCache 1
# Use this to make your cookies persistent (+2 hours here)
PerlSetVar WhatEverExpires +2h
# Use to make AuthCookie send a P3P header with the cookie
# see http://www.w3.org/P3P/ for details about what the value
# of this should be
PerlSetVar WhatEverP3P "CP=\"...\""
# optional: enforce that the destination argument from the login form is
# local to the server
PerlSetVar WhatEverEnforceLocalDestination 1
# optional: specify a default destination for when the destination argument
# of the login form is invalid or unspecified
PerlSetVar WhatEverDefaultDestination /protected/user/
# These documents require user to be logged in.
<Location /protected>
AuthType Sample::Apache::AuthCookieHandler
AuthName WhatEver
PerlAuthenHandler Sample::Apache::AuthCookieHandler->authenticate
PerlAuthzHandler Sample::Apache::AuthCookieHandler->authorize
require valid-user
</Location>
# These documents don't require logging in, but allow it.
<FilesMatch "\.ok$">
AuthType Sample::Apache::AuthCookieHandler
AuthName WhatEver
PerlFixupHandler Sample::Apache::AuthCookieHandler->recognize_user
</FilesMatch>
# This is the action of the login.pl script above.
<Files LOGIN>
AuthType Sample::Apache::AuthCookieHandler
AuthName WhatEver
SetHandler perl-script
PerlHandler Sample::Apache::AuthCookieHandler->login
</Files>
That's the whole config mood. π«Ά
π DESCRIPTION π
Apache::AuthCookie lets you intercept a user's first unauthenticated access to a protected document. The user gets a custom form where they can enter authentication credentials. Those credentials are posted to the server, where AuthCookie verifies them and returns a session key. π
That session key goes back to the user's browser as a cookie. As a cookie, the browser will pass the session key on every subsequent access. AuthCookie will verify the session key and re-authenticate the user. It's giving ticket-based auth, honestly.
All you have to do is write a custom module that inherits from AuthCookie. Your module is a class which implements two methods:
authen_cred()β verify the user-supplied credentials and return a session key. The session key can be any string β often you'll use some string containing username, timeout info, and any other information you need to determine access to documents, and append a one-way hash of those values together with some secret key.authen_ses_key()β verify the session key (previously generated byauthen_cred(), possibly during a previous request) and return the user ID. This user ID will be fed to$r->connection->user()to set Apache's idea of who's logged in.
By using AuthCookie versus Apache's built-in AuthBasic you can design your own authentication system. There are several benefits. β¨
- The client doesn't have to pass the user credentials on every subsequent access. If you're using passwords, this means that the password can be sent on the first request only, and subsequent requests don't need to send this (potentially sensitive) information. This is known as "ticket-based" authentication.
- When you determine that the client should stop using the credentials/session key, the server can tell the client to delete the cookie. Letting users "log out" is a notoriously impossible-to-solve problem of AuthBasic. π
- AuthBasic dialog boxes are ugly. You can design your own HTML login forms when you use AuthCookie. π
- You can specify the domain of a cookie using PerlSetVar commands. For instance, if your AuthName is "WhatEver", you can put the command
PerlSetVar WhatEverDomain .yourhost.com
into your server setup file and your access cookies will span all hosts ending in .yourhost.com.
- You can optionally specify the name of your cookie using the
CookieNamedirective. For instance, if your AuthName is "WhatEver", you can put the command
PerlSetVar WhatEverCookieName MyCustomName
into your server setup file and your cookies for this AuthCookie realm will be named MyCustomName. Default is AuthType_AuthName.
- By default users must satisfy ALL of the
requiredirectives. If you want authentication to succeed if ANYrequiredirectives are met, use theSatisfydirective. For instance, if your AuthName is "WhatEver", you can put the command
PerlSetVar WhatEverSatisfy Any
into your server startup file and authentication for this realm will succeed if ANY of the require directives are met.
This is the flow of the authentication handler, less the details of the redirects. Two REDIRECTs are used to keep the client from displaying the user's credentials in the Location field. They don't really change AuthCookie's model, but they do add another round-trip request to the client.
(-----------------------) +---------------------------------+
( Request a protected ) | AuthCookie sets custom error |
( page, but user hasn't )---->| document and returns |
( authenticated (no ) | FORBIDDEN. Apache abandons |
( session key cookie) ) | current request and creates sub |
(-----------------------) | request for the error document. |<-+
| Error document is a script that | |
| generates a form where the user | |
return | enters authentication | |
^------------------->| credentials (login & password). | |
/ \ False +---------------------------------+ |
/ \ | |
/ \ | |
/ \ V |
/ \ +---------------------------------+ |
/ Pass \ | User's client submits this form | |
/ user's \ | to the LOGIN URL, which calls | |
| credentials |<------------| AuthCookie->login(). | |
\ to / +---------------------------------+ |
\authen_cred/ |
\ function/ |
\ / |
\ / |
\ / +------------------------------------+ |
\ / return | Authen cred returns a session | +--+
V------------->| key which is opaque to AuthCookie.*| |
True +------------------------------------+ |
| |
+--------------------+ | +---------------+
| | | | If we had a |
V | V | cookie, add |
+----------------------------+ r | ^ | a Set-Cookie |
| If we didn't have a session| e |T / \ | header to |
| key cookie, add a | t |r / \ | override the |
| Set-Cookie header with this| u |u / \ | invalid cookie|
| session key. Client then | r |e / \ +---------------+
| returns session key with | n | / pass \ ^
| successive requests | | / session \ |
+----------------------------+ | / key to \ return |
| +-| authen_ses_key|------------+
V \ / False
+-----------------------------------+ \ /
| Tell Apache to set Expires header,| \ /
| set user to user ID returned by | \ /
| authen_ses_key, set authentication| \ /
| to our type (e.g. AuthCookie). | \ /
+-----------------------------------+ \ /
V
(---------------------) ^
( Request a protected ) |
( page, user has a )--------------+
( session key cookie )
(---------------------)
- The session key that the client gets can be anything you want. For example, encrypted information about the user, a hash of the username and password (similar in function to Digest authentication), or the user name and password in plain text (similar in function to HTTP Basic authentication).
The only requirement is that the authen_ses_key function that you create must be able to determine if this session_key is valid and map it back to the originally authenticated user ID.
okay so that's part 1, bestie β part 2 is coming, don't wander off π
πΈ METHODS πΈ
okay bestie, this is the part where the magic actually happens β¨ these are the methods you'll be calling, overriding, or crying about at 2am. let's go π
π authen_cred($r, @credentials)
so like. nobody writes this one for you. you have to define this method yourself in your subclass of Apache::AuthCookie, bestie. its whole job is to create the session key that gets preserved in the user's cookie πͺ and here's the tea about the args it gets handed:
sub authen_cred ($$\@) {
my $self = shift; # Package name (same as AuthName directive)
my $r = shift; # Apache request object
my @cred = @_; # Credentials from login form
...blah blah blah, create a session key...
return $session_key;
}
and the only limitation on that session key? you should be able to look at it later and figure out the user's username from it. that's it. the format is entirely on you, no cap β you are responsible for implementing your own session key format π
a typical format is a string containing the username, an expiration time, whatever else you need, plus an MD5 hash of all that data together with a secret key. that hash is what makes sure the user doesn't tamper with the session key π₯ more info in the Eagle book.
π¦ authen_ses_key($r, $session_key)
again: you must define this method yourself in your subclass of Apache::AuthCookie. its job is to peek at a session key and decide if it's valid. if it is, it returns the username of the authenticated user π
sub authen_ses_key ($$$) {
my ($self, $r, $session_key) = @_;
...blah blah blah, check whether $session_key is valid...
return $ok ? $username : undef;
}
optionally, you can return an array of 2 or more items that will get passed to the method custom_errors. it's this method's responsibility to return the correct response to the main Apache module π«Ά
β¨ custom_errors($r,@_)
Note: this interface is experimental.
this method handles the server response for when you wanna use the Apache custom_response method. any suitable response can be used β and this is particularly useful when implementing 'by directory' access control using the user authentication information. i.e. π
/restricted
/one user is allowed access here
/two not here
/three AND here
so the authen_ses_key method would return a normal response when the user tries to access 'one' or 'three', but return (NOT_FOUND, 'File not found') if an attempt was made to access subdirectory 'two'. or, in the case of expired credentials, (AUTH_REQUIRED,'Your session has timed out, you must login again') π
example 'custom_errors'
sub custom_errors {
my ($self,$r,$CODE,$msg) = @_;
# return custom message else use the server's standard message
$r->custom_response($CODE, $msg) if $msg;
return($CODE);
}
where CODE is a valid code from Apache::Constants β
π recognize_user($r)
if the user has provided a valid session key but the document isn't protected, this method will set $r->connection->user anyway. use it as a PerlFixupHandler, unless you have a better idea π€·ββοΈ
π encoding($r): string
return the ${auth_name}Encoding setting that is in effect for this request.
π requires_encoding($r): string
return the ${auth_name}RequiresEncoding setting that is in effect for this request.
π§ decoded_user($r): string
if you have set ${auth_name}Encoding, then this will return the decoded value of $r->connection->user. cute, right?
π decoded_requires($r): arrayref
this method returns the $r->requires array, with the requirement values decoded if ${auth_name}RequiresEncoding is in effect for this request.
πΈ handle_cache(): void
if ${auth_name}Cache is defined, this sets up the response so that the client will not cache the result. it sets no_cache in the apache request object and sends the appropriate headers so that the client will not cache the response π«
π
remove_cookie(): void
adds a Set-Cookie header that tells the client to delete the cookie immediately. bye boo π
π params($r): Apache::AuthCookie::Params
get the params object for this request. that's it, that's the method.
π login($r)
this method handles the submission of the login form. it will call the authen_cred() method, passing it $r and all the submitted data with names like credential_#, where # is a number. these get passed in a simple array, so the prototype is $self->authen_cred($r, @credentials). after calling authen_cred(), we set the user's cookie and redirect to the URL contained in the destination submitted form field π―
π₯ untaint_destination($uri)
this method returns a modified version of the destination parameter before embedding it into the response header. per default it escapes CR, LF and TAB characters of the uri to avoid certain types of security attacks π€ you can override it to more limit the allowed destinations, e.g. only allow relative uris, only special hosts or only a limited set of characters.
π¦ logout($r)
this is simply a convenience method that unsets the session key for you. you can call it in your logout scripts. usually this looks like $r->auth_type->logout($r);.
β authenticate($r)
this method is one you'll use in a server config file (httpd.conf, .htaccess, ...) as a PerlAuthenHandler. if the user provided a session key in a cookie, the authen_ses_key() method will get called to check whether the key is valid. if not, or if there is no key provided, we redirect to the login form π
π login_form()
this method is responsible for displaying the login form. the default implementation will make an internal redirect and display the URL you specified with the PerlSetVar WhatEverLoginScript configuration directive. you can overwrite this method to provide your own mechanism π«
π login_form_status($r)
this method returns the HTTP status code that will be returned with the login form response. the default behaviour is to return FORBIDDEN, except for some known browsers which ignore HTML content for FORBIDDEN responses (e.g.: SymbianOS). you can override this method to return custom codes.
note that FORBIDDEN is the most correct code to return as the given request was not authorized to view the requested page. you should only change this if FORBIDDEN does not work. fr fr.
π§ get_satisfy(): string
get the Satisfy value for the current request, or all if it is not configured.
π authorize($r)
this will step through the require directives you've given for protected documents and make sure the user passes muster π«‘ the require valid-user and require user joey-jojo directives are handled for you. you can implement custom directives, such as require species hamster, by defining a method called species() in your subclass, which will then be called. the method will be called as $r->species($r, $args), where $args is everything on your require line after the word species. the method should return OK on success and FORBIDDEN on failure β οΈ
π send_cookie($session_key)
by default this method simply sends out the session key you give it. if you need to change the default behavior (perhaps to update a timestamp in the key) you can override this method π
πΈ send_p3p(): void
set a P3P response header if ${auth_name}P3P is configured. the value of the header is whatever is in the ${auth_name}P3P setting.
π
cookie_string(%args): string
generate a cookie string. %args are:
requestβ the Apache request objectkeyβ the Cookie namevalueβ the Cookie valueexpires(optional) β when the cookie expires. seeexpires()in Apache::AuthCookie::Util. uses${auth_name}Expiresif not given.
all other cookie settings come from PerlSetVar settings β¨
π key()
this method will return the current session key, if any. this can be handy inside a method that implements a require directive check (like the species method discussed above) if you put any extra information like clearances or whatever into the session key π
π¦ get_cookie_path(): string
returns the value of PerlSetVar ${auth_name}Path.
β¨ EXAMPLE β¨
for an example of how to use Apache::AuthCookie, you may want to check out the test suite, which runs AuthCookie through a few of its paces πββοΈ the documents are located in t/eg/, and you may want to peruse t/real.t to see the generated httpd.conf file (at the bottom of real.t) and check out what requests it's making of the server (at the top of real.t) π
π THE LOGIN SCRIPT π
you will need to create a login script (called login.pl above) that generates an HTML form for the user to fill out. you might generate the page using an Apache::Registry script, or an HTML::Mason component, or perhaps even using a static HTML page. it's usually useful to generate it dynamically so that you can define the 'destination' field correctly (see below) π
the following fields must be present in the form:
- the ACTION of the form must be
/LOGIN(or whatever you defined in your server configuration as handled by the->login()method - see example in the SYNOPSIS section). - the various user input fields (username, passwords, etc.) must be named 'credential_0', 'credential_1', etc. on the form. these will get passed to your
authen_cred()method. - you must define a form field called 'destination' that tells AuthCookie where to redirect the request after successfully logging in. typically this value is obtained from
$r->prev->uri. see thelogin.plscript int/eg/.
in addition, you might want your login page to be able to tell why the user is being asked to log in π€ in other words, if the user sent bad credentials, then it might be useful to display an error message saying that the given username or password are invalid. also, it might be useful to determine the difference between a user that sent an invalid auth cookie, and a user that sent no auth cookie at all. to cope with these situations, AuthCookie will set $r->subprocess_env('AuthCookieReason') to one of the following values.
no_cookieβ the user presented no cookie at all. typically this means the user is trying to log in for the first time πbad_cookieβ the cookie the user presented is invalid. typically this means that the user is not allowed access to the given page π«bad_credentialsβ the user tried to log in, but the credentials that were passed are invalid π
you can examine this value in your login form by examining $r->prev->subprocess_env('AuthCookieReason') (because it's a sub-request π).
of course, if you want to give more specific information about why access failed when a cookie is present, your authen_ses_key() method can set arbitrary entries in $r->subprocess_env π
π THE LOGOUT SCRIPT
okay so if you wanna let your users dip out on their own (which, fun fact, Basic Auth will never let you do, it's giving clingy situationship), you gotta make a logout script. for inspo, peek at t/htdocs/docs/logout.pl. logout scripts will probably wanna use AuthCookie's logout() method, because it sets the proper cookie headers to clear the user's cookie. it usually looks like this:
$r->auth_type->logout($r);
β οΈ real talk bestie: if you don't fully trust your users (and lowkey why would you), do not count on cookie deletion alone for logging out. you'll have to expire some server-side login info too. AuthCookie is not doing that for you β that part is all you, babes. π
π€ ENCODING AND CHARACTER SETS
Encoding β¨
AuthCookie can decode POST/GET data for you, but only if you tell it what the client encoding is. you do that by setting the ${auth_name}Encoding setting in httpd.conf. like so:
PerlSetVar WhateEverEncoding UTF-8
# and you also need to arrange for charset=UTF-8 at the end of the
# Content-Type header with something like:
AddDefaultCharset UTF-8
ngl you can use charsets other than UTF-8, but then you have to arrange for the browser to send the right encoding back to the server. no cap, that part's on you.
if you've turned on Encoding support by setting ${auth_name}Encoding, here's the whole vibe check of what happens:
- the internal pure-perl params processing subclass gets used, even if libapreq is installed. because libapreq simply does not handle encoding, periodt.
- POST/GET data intercepted by AuthCookie gets decoded into perl's internal format using
decodein Encode. - the value stored in
$r->connection->userwill be encoded as bytes, not characters, using the configured encoding name. why? because the value mod_perl stores is a C API string, not a perl string. if you want the user string encoded with character semantics, usedecoded_user()instead. π¦
and yeah, this does have some caveats (we stay honest in this house):
- your
authen_cred()andauthen_ses_key()function is expected to return a decoded username, either by passing it throughdecode()in Encode, or by turning on the UTF8 flag if appropriate. - due to the way HTTP works, cookies cannot contain non-ASCII characters. so if you're including the username in your generated session key, you'll need to escape any non-ascii characters in the session key returned by
authen_cred(). - similarly, you must reverse this escaping process in
authen_ses_key()and return adecode()in Encode decoded username. if yourauthen_cred()function already only generates ASCII-only session keys, then honestly don't worry about any of this, you're fine. π - the value stored in
$r->connection->userwill be encoded using bytes semantics using the configured Encoding. if you want the decoded user value, usedecoded_user()instead.
Requires πΈ
you can also specify what the charset is of the Apache $r->requires data by setting ${auth_name}RequiresEncoding in httpd.conf.
Example time:
PerlSetVar WhatEverRequiresEncoding UTF-8
this makes it so AuthCookie decodes your requires directives using the configured character set. you really only need this if you've used non-ascii characters in any of your requires directives in httpd.conf. like:
requires user programmΓΈr
π ABOUT SESSION KEYS
unlike the sample AuthCookieHandler, you have to verify the user's login and password in authen_cred(), and then you do something like:
my $date = localtime;
my $ses_key = MD5->hexhash(join(';', $date, $PID, $PAC));
then you save $ses_key along with the user's login, and return $ses_key. iconic behavior, truly.
now authen_ses_key() looks up the $ses_key passed to it and returns the saved login. the original author uses Oracle to store the session key and retrieve it later β see the ToDo section below for some other ideas. π
TO DO π
- it might be nice if the logout method could accept some parameters that could make it easy to redirect the user to another URI, or whatever. but honestly, they'd have to think about the options needed before implementing anything, though. fair, bestie, fair.
π HISTORY
Originally written by Eric Bartley <bartley@purdue.edu>
versions 2.x were written by Ken Williams <ken@forum.swarthmore.edu>
π SEE ALSO
perl(1), mod_perl(1), Apache(1).
π SOURCE
The development version is on github at <https://github.com/mschout/apache-authcookie> and may be cloned from <https://github.com/mschout/apache-authcookie.git>
π BUGS
Please report any bugs or feature requests on the bugtracker website <https://github.com/mschout/apache-authcookie/issues>
When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature. we love a reproducible lil receipt π§Ύβ¨
π AUTHOR
Michael Schout <mschout@cpan.org>
π COPYRIGHT AND LICENSE
This software is copyright (c) 2000 by Ken Williams.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. slay, truly the most generous license energy. π
and that's a wrap on this whole page, bestie!! π«Ά this was perl v5.40.1, dated 2025-09-30, and it's the Apache...Cookie(3pm) manual page β go forth and authenticate responsibly, mwah π
β¨
π¦ where this page comes from
- ubuntu resolute: libapache2-authcookie-perl 3.32-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libapache2-authcookie-perl 3.32-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms