Apache-AuthCookie
view release on metacpan or search on metacpan
lib/Apache/AuthCookie.pm view on Meta::CPAN
return DECLINED if is_blank($auth_type) or is_blank($auth_name);
return DECLINED if is_blank($r->header_in('Cookie'));
my $cookie_name = $self->cookie_name($r);
my ($cookie) = $r->header_in('Cookie') =~ /$cookie_name=([^;]+)/;
$r->log_error("cookie $cookie_name is $cookie") if $debug >= 2;
return DECLINED unless $cookie;
my ($user, @args) = $auth_type->authen_ses_key($r, $cookie);
if (!is_blank($user) and scalar @args == 0) {
$r->log_error("user is $user") if $debug >= 2;
# if SessionTimeout is on, send new cookie with new Expires.
if (my $expires = $r->dir_config("${auth_name}SessionTimeout")) {
$self->send_cookie($cookie, { expires => $expires });
}
$r->connection->user( $self->_encode($r, $user) );
}
elsif (scalar @args > 0 and $auth_type->can('custom_errors')) {
return $auth_type->custom_errors($r, $user, @args);
}
return is_blank($user) ? DECLINED : OK;
}
sub cookie_name {
my ($self, $r) = @_;
my $auth_type = $r->auth_type;
my $auth_name = $r->auth_name;
my $cookie_name = $r->dir_config("${auth_name}CookieName")
|| "${auth_type}_${auth_name}";
return $cookie_name;
}
sub encoding {
my ($self, $r) = @_;
my $auth_name = $r->auth_name;
return $r->dir_config("${auth_name}Encoding");
}
sub requires_encoding {
my ($self, $r) = @_;
my $auth_name = $r->auth_name;
return $r->dir_config("${auth_name}RequiresEncoding");
}
sub decoded_user {
my ($self, $r) = @_;
my $user = $r->connection->user;
if (is_blank($user)) {
return $user;
}
my $encoding = $self->encoding($r);
if (!is_blank($encoding)) {
$user = Encode::decode($encoding, $user);
}
return $user;
}
sub decoded_requires {
my ($self, $r) = @_;
my $reqs = $r->requires or return;
my $encoding = $self->requires_encoding($r);
unless (is_blank($encoding)) {
for my $req (@$reqs) {
$$req{requirement} = Encode::decode($encoding, $$req{requirement});
}
}
return $reqs;
}
sub handle_cache {
my $self = shift;
my $r = Apache->request;
my $auth_name = $r->auth_name;
return unless $auth_name;
unless ($r->dir_config("${auth_name}Cache")) {
$r->no_cache(1);
$r->err_header_out(Pragma => 'no-cache');
}
}
sub remove_cookie {
my $self = shift;
my $r = Apache->request;
my $debug = $r->dir_config("AuthCookieDebug") || 0;
my $cookie_name = $self->cookie_name($r);
my $str = $self->cookie_string(
request => $r,
key => $cookie_name,
value => '',
expires => 'Mon, 21-May-1971 00:00:00 GMT'
);
$r->err_headers_out->add("Set-Cookie" => "$str");
$r->log_error("removed cookie $cookie_name") if $debug >= 2;
}
# convert current request to GET
sub _convert_to_get {
my ($self, $r) = @_;
return unless $r->method eq 'POST';
my $debug = $r->dir_config("AuthCookieDebug") || 0;
$r->log_error("Converting POST -> GET") if $debug >= 2;
lib/Apache/AuthCookie.pm view on Meta::CPAN
else {
$r->custom_response($status, $authen_script);
}
return $status;
}
sub login_form_status {
my ($self, $r) = @_;
my $ua = $r->headers_in->get('User-Agent')
or return FORBIDDEN;
if (Apache::AuthCookie::Util::understands_forbidden_response($ua)) {
return FORBIDDEN;
}
else {
return OK;
}
}
sub satisfy_is_valid {
my ($auth_type, $r, $satisfy) = @_;
$satisfy = lc $satisfy;
if ($satisfy eq 'any' or $satisfy eq 'all') {
return 1;
}
else {
my $auth_name = $r->auth_name;
$r->log_reason("PerlSetVar ${auth_name}Satisfy $satisfy invalid",
$r->uri);
return 0;
}
}
sub get_satisfy {
my ($auth_type, $r) = @_;
my $auth_name = $r->auth_name;
return lc $r->dir_config("${auth_name}Satisfy") || 'all';
}
sub authorize ($$) {
my ($auth_type, $r) = @_;
my $debug = $r->dir_config("AuthCookieDebug") || 0;
$r->log_error('authorize() for ' . $r->uri()) if ($debug >= 3);
return OK unless $r->is_initial_req; #only the first internal request
if ($r->auth_type ne $auth_type) {
$r->log_error($auth_type . " auth type is " . $r->auth_type)
if ($debug >= 3);
return DECLINED;
}
my $reqs_arr = $auth_type->decoded_requires($r) or return DECLINED;
my $user = $auth_type->decoded_user($r);
if (is_blank($user)) {
# authentication failed
$r->log_reason("No user authenticated", $r->uri);
return FORBIDDEN;
}
my $satisfy = $auth_type->get_satisfy($r);
return SERVER_ERROR unless $auth_type->satisfy_is_valid($r, $satisfy);
my $satisfy_all = $satisfy eq 'all';
my ($forbidden);
foreach my $req (@$reqs_arr) {
my ($requirement, $args) = split /\s+/, $req->{requirement}, 2;
$args = '' unless defined $args;
$r->log_error("requirement := $requirement, $args") if $debug >= 2;
if (lc($requirement) eq 'valid-user') {
if ($satisfy_all) {
next;
}
else {
return OK;
}
}
if ($requirement eq 'user') {
if ($args =~ m/\b$user\b/) {
next if $satisfy_all;
return OK; # satisfy any
}
$forbidden = 1;
next;
}
# Call a custom method
my $ret_val = $auth_type->$requirement($r, $args);
$r->log_error("$auth_type->$requirement returned $ret_val")
if $debug >= 3;
if ($ret_val == OK) {
next if $satisfy_all;
return OK; # satisfy any
}
# Nothing succeeded, deny access to this user.
$forbidden = 1;
}
return $forbidden ? FORBIDDEN : OK;
}
sub send_cookie {
my ($self, $ses_key, $cookie_args) = @_;
my $r = Apache->request();
$cookie_args = {} unless defined $cookie_args;
my $cookie_name = $self->cookie_name($r);
lib/Apache/AuthCookie.pm view on Meta::CPAN
You must define this method yourself in your subclass of
Apache::AuthCookie. Its job is to look at a session key and determine
whether it is 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, return an array of 2 or more items that will be passed to method
custom_errors. It is the responsibility of this method to return the correct
response to the main Apache module.
=head2 custom_errors($r,@_)
Note: this interface is experimental.
This method handles the server response when you wish 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 Apache::Constants
=head2 recognize_user($r)
If the user has provided a valid session key but the document isn't
protected, this method will set C<$r-E<gt>connection-E<gt>user>
anyway. Use it as a PerlFixupHandler, unless you have a better idea.
=head2 encoding($r): string
Return the ${auth_name}Encoding setting that is in effect for this request.
=head2 requires_encoding($r): string
Return the ${auth_name}RequiresEncoding setting that is in effect for this request.
=head2 decoded_user($r): string
If you have set ${auth_name}Encoding, then this will return the decoded value of
C<< $r->connection->user >>.
=head2 decoded_requires($r): arrayref
This method returns the C<< $r->requires >> array, with the C<requirement>
values decoded if C<${auth_name}RequiresEncoding> is in effect for this
request.
=head2 handle_cache(): void
If C<${auth_name}Cache> is defined, this sets up the response so that the
client will not cache the result. This sents C<no_cache> in the apache request
object and sends the appropriate headers so that the client will not cache the
response.
=head2 remove_cookie(): void
Adds a C<Set-Cookie> header that instructs the client to delete the cookie
immediately.
=head2 params($r): Apache::AuthCookie::Params
Get the params object for this request.
=head2 login($r)
This method handles the submission of the login form. It will call
the C<authen_cred()> method, passing it C<$r> and all the submitted
data with names like C<"credential_#">, where # is a number. These will
be passed in a simple array, so the prototype is
C<$self-E<gt>authen_cred($r, @credentials)>. After calling
C<authen_cred()>, we set the user's cookie and redirect to the
URL contained in the C<"destination"> submitted form field.
=head2 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 limited set of characters.
=head2 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
C<$r-E<gt>auth_type-E<gt>logout($r);>.
=head2 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 C<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.
=head2 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 C<PerlSetVar WhatEverLoginScript> configuration
directive. You can overwrite this method to provide your own
mechanism.
=head2 login_form_status($r)
lib/Apache/AuthCookie.pm view on Meta::CPAN
The cookie the user presented is invalid. Typically this means that the user
is not allowed access to the given page.
=item I<bad_credentials>
The user tried to log in, but the credentials that were passed are invalid.
=back
You can examine this value in your login form by examining
C<$r-E<gt>prev-E<gt>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 C<authen_ses_key()>
method can set arbitrary entries in C<$r-E<gt>subprocess_env>.
=head1 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 C<logout()> method, which will set the
proper cookie headers in order to clear the user's cookie. This
usually looks like C<$r-E<gt>auth_type-E<gt>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.
=head1 ENCODING AND CHARACTER SETS
=head2 Encoding
AuthCookie provides support for decoding POST/GET data if you tell it what the
client encoding is. You do this by setting the C<< ${auth_name}Encoding >>
setting in C<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 B<can> use charsets other than C<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 C<< ${auth_name}Encoding >>,
this has the following effects:
=over 4
=item *
The internal pure-perl params processing subclass will be used, even if
libapreq is installed. libapreq does not handle encoding.
=item *
POST/GET data intercepted by AuthCookie will be decoded to perl's internal
format using L<Encode/decode>.
=item *
The value stored in C<< $r-E<gt>connection-E<gt>user >> will be encoded as
B<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 L</decoded_user()> to get user string encoded using B<character> semantics.
=back
This does has some caveats:
=over 4
=item *
your L</authen_cred()> and L</authen_ses_key()> function is expected to return
a decoded username, either by passing it through L<Encode/decode()>, or, by
turning on the UTF8 flag if appropriate.
=item *
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 L</authen_cred()>.
=item *
Similarly, you must reverse this escaping process in L</authen_ses_key()> and
return a L<Encode/decode()> decoded username. If your L</authen_cred()>
function already only generates ASCII-only session keys then you do not need to
worry about any of this.
=item *
The value stored in C<< $r-E<gt>connection-E<gt>user >> will be encoded using
bytes semantics using the configured B<Encoding>. If you want the decoded user
value, use L</decoded_user()> instead.
=back
=head2 Requires
You can also specify what the charset is of the Apache C<< $r-E<gt>requires >>
data is by setting C<< ${auth_name}RequiresEncoding >> in httpd.conf.
E.g.:
PerlSetVar WhatEverRequiresEncoding UTF-8
This will make it so that AuthCookie will decode your C<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 C<requires> directives in
httpd.conf. e.g.:
requires user programmør
=head1 ABOUT SESSION KEYS
Unlike the sample AuthCookieHandler, you have you verify the user's
login and password in C<authen_cred()>, then you do something
like:
my $date = localtime;
my $ses_key = MD5->hexhash(join(';', $date, $PID, $PAC));
save C<$ses_key> along with the user's login, and return C<$ses_key>.
Now C<authen_ses_key()> looks up the C<$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.
=head2 TO DO
=over 4
=item *
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.
=back
=head1 HISTORY
Originally written by Eric Bartley <bartley@purdue.edu>
versions 2.x were written by Ken Williams <ken@forum.swarthmore.edu>
=head1 SEE ALSO
L<perl(1)>, L<mod_perl(1)>, L<Apache(1)>.
=head1 SOURCE
The development version is on github at L<https://github.com/mschout/apache-authcookie>
( run in 2.267 seconds using v1.01-cache-2.11-cpan-6aa56a78535 )