Apache...hCookie(3pm)

๐Ÿ“ฆ
version 3.32 ยท 5 versions
, in ubuntu resolute, ubuntu stonking

๐Ÿ’– Apache2::AuthCookie(3pm) ๐Ÿ’–

User Contributed Perl Documentation ยท 3pm โ€” perl module manpage

okay so bestie, sit down, hydrate ๐Ÿ“, because this is the one that makes cookie-based auth in mod_perl actually make sense. we're doing this in chunks so nobody's brain melts.


๐ŸŒธ NAME ๐ŸŒธ

Apache2::AuthCookie โ€” Perl Authentication and Authorization via cookies

like, that's it. that's the whole job. auth via cookies. iconic career honestly ๐Ÿ’…


๐ŸŽ€ VERSION ๐ŸŽ€

version 3.32


๐Ÿฆ‹ SYNOPSIS ๐Ÿฆ‹

first thing, no cap: your mod_perl has to be at least 2.0.0-RC5, and it needs StackedHandlers, MethodHandlers, Authen, and Authz compiled in. that's the entry fee. if those aren't in there, we're not doing anything today, sorry ๐Ÿซถ

so here's the setup, dropped into httpd.conf or .htaccess:

# In httpd.conf or .htaccess:
PerlModule Sample::Apache2::AuthCookieHandler
PerlSetVar WhatEverPath /
PerlSetVar WhatEverLoginScript /login.pl

that's your handler module, your path (WhatEverPath) and the login script that gets hit (WhatEverLoginScript). everything below is PerlSetVar knobs, and yes they all wear the WhatEver prefix because that's your AuthName, iykyk.

# 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

quick translation bestie ๐Ÿงš:

  • WhatEverSatisfy changes how require directives get matched โ€” set it to Any and matching any one of them is enough, set it to All and you have to match all of them. the default is All.
  • WhatEverDomain is optional and lets you set the domain scope of the cookie. default is the current domain.
  • WhatEverSecure โ†’ only send it over a secure connection ๐Ÿ”ฅ
  • WhatEverSessionTimeout kills the user session cookie if they haven't hit an auth-required or recognize_user page in a while โ€” and when it's set, every request sets a brand new cookie with an updated expire time.

more knobs, keep scrolling:

# 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

# to enable the SameSite cookie property, set SameSite to "lax" or "strict".
# See: https://www.owasp.org/index.php/SameSite
PerlSetVar WhatEverSameSite strict

# 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=\"...\""
  • WhatEverHttpOnly turns on the HttpOnly cookie property. heads up: this is an MS extension, and the docs point you at that msdn link for details.
  • WhatEverSameSite turns on the SameSite cookie property โ€” set it to "lax" or "strict". OWASP link provided, go read it, it's giving security awareness โœจ
  • WhatEverCache โ€” usually documents are uncached, so turn it off here.
  • WhatEverExpires makes your cookies persistent (+2h in the example).
  • WhatEverP3P makes AuthCookie send a P3P header along with the cookie โ€” the w3.org link has the details on what that value should actually be.

and the "optional" girlies, the ones who show up when they feel like it:

# optional: enable decoding of intercepted GET/POST params:
PerlSetVar WhatEverEncoding UTF-8

# optional: enable decoding of httpd.conf "Requires" directives
PerlSetVar WhatEverRequiresEncoding UTF-8

# 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/
  • WhatEverEncoding turns on decoding of intercepted GET/POST params.
  • WhatEverRequiresEncoding turns on decoding of httpd.conf Requires directives.
  • WhatEverEnforceLocalDestination enforces that the destination argument coming from the login form is local to the server. yes bestie, that one's for the people trying to be cute with redirects ๐Ÿ™ˆ
  • WhatEverDefaultDestination gives you a fallback destination for when the login form's destination argument is invalid or just not there.

now the actual <Location> blocks, where the auth stuff lives:

# These documents require user to be logged in.
<Location /protected>
 AuthType Sample::Apache2::AuthCookieHandler
 AuthName WhatEver
 PerlAuthenHandler Sample::Apache2::AuthCookieHandler->authenticate
 PerlAuthzHandler Sample::Apache2::AuthCookieHandler->authorize
 require valid-user
</Location>

/protected = login required, periodt. authenticate handles the authen, authorize handles the authz, and require valid-user gates the whole thing ๐Ÿ‘‘

# These documents don't require logging in, but allow it.
<FilesMatch "\.ok$">
 AuthType Sample::Apache2::AuthCookieHandler
 AuthName WhatEver
 PerlFixupHandler Sample::Apache2::AuthCookieHandler->recognize_user
</FilesMatch>

these documents don't require logging in, they just allow it โ€” that's recognize_user doing its thing in a PerlFixupHandler, matched on "\.ok$".

# This is the action of the login.pl script above.
<Files LOGIN>
 AuthType Sample::Apache2::AuthCookieHandler
 AuthName WhatEver
 SetHandler perl-script
 PerlResponseHandler Sample::Apache2::AuthCookieHandler->login
</Files>

and this <Files LOGIN> block is the action of that login.pl script from the top โ€” SetHandler perl-script plus PerlResponseHandler ...->login, and the login flow goes brrr ๐Ÿ’œ

๐Ÿ’– DESCRIPTION ๐Ÿ’–

okay so bestie, first things first โ€” this module is for mod_perl version 2 โœจ. If you're running mod_perl version 1, you should be using Apache::AuthCookie instead, no cap. Different girl, different era ๐Ÿ’…

Apache2::AuthCookie lets you intercept a user's first unauthenticated access to a protected document, like a bouncer at the club door but make it โœจcodeโœจ. The user gets presented with a custom form where they can enter authentication credentials. Then those credentials get 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 ๐Ÿช. And because it's 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 "remember me" but actually functional. Iconic.


All you have to do is write a custom module that inherits from AuthCookie ๐Ÿซถ. Your module is a class which implements two methods, and honestly that's the whole vibe:

  • 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 ๐Ÿ”. Go off, design queen.
  • authen_ses_key() Verify the session key (previously generated by authen_cred(), possibly during a previous request) and return the user ID. This user ID will be fed to $r->user() to set Apache's idea of who's logged in. Main character energy fr fr.

By using AuthCookie versus Apache's built-in AuthBasic you can design your own authentication system ๐ŸŒˆ. There are several benefits, and bestie, we're listing every single one:

  1. 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 ๐ŸŽŸ๏ธโœจ.
  2. 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 ๐Ÿ’€. Not us though. We solved it.
  3. AuthBasic dialog boxes are ugly ๐Ÿ™ˆ. You can design your own HTML login forms when you use AuthCookie. Aesthetic matters, periodt.
  4. 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 ๐ŸŒ.

  1. You can optionally specify the name of your cookie using the "CookieName" directive. 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. She has a name and it's cute.

  1. By default users must satisfy ALL of the "require" directives. If you want authentication to succeed if ANY "require" directives are met, use the "Satisfy" directive. 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 ๐Ÿ”ฅ.


okay so here's the flow of the authentication handler, minus the details of the redirects. Two HTTP_MOVED_TEMPORARILY's 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. Buckle up bestie, this ASCII art is a whole journey ๐Ÿฆ‹
 (-----------------------)     +---------------------------------+
 ( Request a protected   )     | AuthCookie sets custom error    |
 ( page, but user hasn't )---->| document and returns            |
 ( authenticated (no     )     | HTTP_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). Sky's the limit, do your thing ๐Ÿ’…

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 ๐ŸŽฏ. That's the whole assignment bestie, no shortcuts.

๐Ÿ’… METHODS ๐Ÿ’…

๐Ÿ” authorize(): int

okay so this is the bouncer at the club ๐Ÿšชโœจ It walks through all the require directives you set up for your protected docs and makes sure the user actually passes muster.

The require valid-user and require user joey-jojo directives? Handled for you, bestie, no cap. ๐Ÿ’–

Wanna do a custom directive, like require species hamster? Slay, just define a method called species() in your subclass and it'll get called for you. It gets called as $r->species($r, $args), where $args is literally everything on your require line after the word species. Return OK on success and HTTP_FORBIDDEN on failure. periodt. ๐Ÿ”ฅ

๐ŸŒธ get_satisfy(): string

Grabs the value of ${auth_name}Satisfy, or all if it's not set. default vibes โœจ

๐Ÿฆ‹ satisfy_is_valid(): bool

Returns true if the configured ${auth_name}Satisfy is valid, false otherwise. that's it, that's the whole method ๐Ÿ’€

๐Ÿ’– authen_cred(): string

You must define this one yourself in your subclass of Apache2::AuthCookie. Its whole job is to create the session key that gets preserved in the user's cookie. ๐Ÿช

The arguments that get passed to it are:

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;
}

The only limitation on the session key is that you should be able to look at it later and determine the user's username. Everything else is on you โ€” you're responsible for implementing your own session key format, bestie ๐Ÿซถ

A typical format is making a string that contains the username, an expiration time, whatever else you need, and an MD5 hash of all that data together with a secret key. That hash is the icon that ensures the user doesn't tamper with the session key ๐Ÿ‘‘ More info in the Eagle book.

๐Ÿ”‘ authen_ses_key($r, $session_key): string

Also must be defined by you, in your subclass of Apache2::AuthCookie. Its job is to look at a session key and figure out whether it's valid. If so, 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 is the responsibility of this method to return the correct response to the main Apache module. ๐ŸŒˆ

๐Ÿ™ˆ custom_errors($r,@_): int

Note: this interface is experimental. โš ๏ธ

This method handles the server response when you want to access the Apache custom_response method. Any suitable response can be used. 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

The authen_ses_key method would return a normal response when the user attempts 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 Apache2::Const

๐Ÿงš ENCODING AND CHARACTER SETS ๐Ÿงš

โœจ Encoding

AuthCookie supports decoding POST/GET data if you tell it what the client encoding is. You do that by setting the ${auth_name}Encoding setting in httpd.conf. E.g.:

 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

Note that you can use charsets other than UTF-8, however, you need to arrange for the browser to send the right encoding back to the server. ๐Ÿซถ

If you have turned on Encoding support by setting ${auth_name}Encoding, this has the following effects:

  • The internal pure-perl params processing subclass will be used, even if libapreq2 is installed. libapreq2 does not have any support for encoding or unicode.
  • POST/GET data intercepted by AuthCookie will be decoded to perl's internal format using decode in Encode.
  • The value stored in $r->user will be encoded as bytes, not characters using the configured encoding name. This is because the value stored by mod_perl is a C API string, and not a perl string. You can use decoded_user() to get user string encoded using character semantics.

This does has some caveats: ๐Ÿ’€

  • your authen_cred() and authen_ses_key() function is expected to return a decoded username, either by passing it through decode() in Encode, or, by turning on the UTF8 flag if appropriate.
  • Due to the way HTTP works, cookies cannot contain non-ASCII characters. Because of this, if you are including the username in your generated session key, you will 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 a decode() in Encode decoded username. If your authen_cred() function already only generates ASCII-only session keys then you do not need to worry about any of this.
  • The value stored in $r->user will be encoded using bytes semantics using the configured Encoding. If you want the decoded user value, use decoded_user() instead.

๐ŸŒธ Requires

You can also specify what the charset is of the Apache $r->requires data is by setting ${auth_name}RequiresEncoding in httpd.conf.

E.g.:

 PerlSetVar WhatEverRequiresEncoding UTF-8

This will make it so that AuthCookie will decode your requires directives using the configured character set. You really only need to do this if you have used non-ascii characters in any of your requires directives in httpd.conf. e.g.:

 requires user programmรธr

๐ŸŽ€ EXAMPLE ๐ŸŽ€

For an example of how to use Apache2::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). go look, it's giving study guide energy ๐Ÿ“šโœจ


๐Ÿ’œ 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 a ModPerl::Registry script, a HTML::Mason component, an Apache handler, 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:

  1. 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).
  2. 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.
  3. 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 the login.pl script in t/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 ๐Ÿšช

If you want to let users log themselves out (something that can't be done using Basic Auth), you need to create a logout script. For an example, see t/htdocs/docs/logout.pl. Logout scripts may want to take advantage of AuthCookie's logout() method, which will set the proper cookie headers in order to clear the user's cookie. This usually looks like $r->auth_type->logout($r);. ๐Ÿช๐Ÿ’จ

Note that if you don't necessarily trust your users, you can't count on cookie deletion for logging out. You'll have to expire some server-side login information too. AuthCookie doesn't do this for you, you have to handle it yourself. no shortcuts bestie ๐Ÿ˜ญ

๐Ÿ”ฎ ABOUT SESSION KEYS ๐Ÿ”ฎ

Unlike the sample AuthCookieHandler, you have you verify the user's login and password in authen_cred(), then you do something like:

    my $date = localtime;
    my $ses_key = MD5->hexhash(join(';', $date, $PID, $PAC));

save $ses_key along with the user's login, and return $ses_key. ๐Ÿ’พ

Now authen_ses_key() looks up the $ses_key passed to it and returns the saved login. I use 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. I'd have to think about the options needed before I implement anything, though. ๐Ÿ’ญ

๐Ÿ“œ HISTORY ๐Ÿ“œ

Originally written by Eric Bartley <bartley@purdue.edu>

versions 2.x were written by Ken Williams <ken@forum.swarthmore.edu>


Copyright (c) 2000 Ken Williams. All rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


๐Ÿ‘€ SEE ALSO ๐Ÿ‘€

Apache2::AuthCookie::Base


๐ŸŒˆ 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 (bestie, pls tell us)

Found a bug? Got a feature request burning a hole in your notes app? Please report any bugs or feature requests on the bugtracker website <https://github.com/mschout/apache-authcookie/issues> โ€” that's the spot, that's the place, that's the whole vibe. ๐Ÿ’–

And when you do slide into that issue tracker, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature. fr fr, this is not a suggestion, this is the assignment โ€” a failing test is the love language of every maintainer alive. It's giving "here's exactly what's broken" and honestly? Iconic. ๐Ÿ”ฅ


๐Ÿ‘‘ AUTHOR

Michael Schout <mschout@cpan.org> โ€” the author, the moment, the main character. Say thank you. ๐Ÿซถ


So here's the legal tea, and we keep it exact because that's how it works:

  • 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. ๐Ÿ’…

That's it, that's the whole license. Redistribute it, remix it, just keep it under the same Perl 5 terms. No cap. ๐ŸŽ€


And that's a wrap on the whole page, bestie! This version shipped with perl v5.40.1 and is dated 2025-09-30 โ€” yeah, that's the timestamp on the doorframe. Go forth, authenticate your cookies, and stay slay. ๐ŸŒˆ๐Ÿฆ‹๐Ÿ’–

๐Ÿ“ฆ where this page comes from