view release on metacpan or search on metacpan
t/samples/httpd-2.4.38/http_config.h view on Meta::CPAN
/** A pointer to the next module in the list
* @var module_struct *next
*/
struct module_struct *next;
/** Magic Cookie to identify a module structure; It's mainly
* important for the DSO facility (see also mod_so). */
unsigned long magic;
/** Function to allow MPMs to re-write command line arguments. This
* hook is only available to MPMs.
view all matches for this distribution
view release on metacpan or search on metacpan
use strict;
our $VERSION = '1.0.2';
$SIG{__WARN__} = sub { };
sub getCookies {
# cookies are seperated by a semicolon and a space, this will split
# them and return a hash of cookies
my(@rawCookies) = split (/; /,$ENV{'HTTP_COOKIE'});
my(%cookies);
my($key,$val);
foreach(@rawCookies){
($key, $val) = split (/=/,$_);
$cookies{$key} = $val;
}
return %cookies;
See all functions
=head1 METHODS
=head2 getCookies()
Retrieves any cookie information from the browser
%cookies = Ananke::Utils::getCookies;
=head2 getTime(timestamp)
Return time in hh:mm:ss
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AnnoCPAN/Control.pm view on Meta::CPAN
use strict;
use warnings;
no warnings 'uninitialized';
use AnnoCPAN::Config;
use AnnoCPAN::DBI;
use CGI::Cookie;
use Digest::MD5 qw(md5_hex);
use IO::String;
use POSIX qw(ceil);
use Lingua::EN::Inflect qw(NO);
use AnnoCPAN::Feed;
lib/AnnoCPAN/Control.pm view on Meta::CPAN
defined $value ? $value->value : AnnoCPAN::Config->option($name);
}
=item $obj->cookies
Return an arrayref with the current cookies (which are L<CGI::Cookie> objects).
=cut
sub cookies {
my ($self) = @_;
lib/AnnoCPAN/Control.pm view on Meta::CPAN
sub add_cookie {
my ($self, $name, $val) = @_;
my $max_time = AnnoCPAN::Config->option('cookie_duration');
push @{$self->{cookies}}, CGI::Cookie->new(
-name => $name, -value => $val,
$max_time ? (-expires => "+${max_time}d") : (),
);
}
lib/AnnoCPAN/Control.pm view on Meta::CPAN
=cut
sub delete_cookie {
my ($self, $name) = @_;
push @{$self->{cookies}}, CGI::Cookie->new(
-name => $name, -value => '', -expires => '-1Y',
);
}
=item $obj->check_login
lib/AnnoCPAN/Control.pm view on Meta::CPAN
sub check_login {
my ($self) = @_;
if ($ENV{TEST_USER}) {
return AnnoCPAN::DBI::User->retrieve(username => 'test');
}
my %cookies = CGI::Cookie->fetch;
my $login = $cookies{login} && $cookies{login}->value;
my $time = $cookies{'time'} && $cookies{'time'}->value;
my $key = $cookies{key} && $cookies{key}->value;
my $max_time = (AnnoCPAN::Config->option('cookie_duration') || 1E9) * 86400;
if ($self->key($login, $time) eq $key and time-$time < $max_time) {
view all matches for this distribution
view release on metacpan or search on metacpan
lib/Any/Renderer/Data/Serializer.pm view on Meta::CPAN
my @dirs = File::Spec->splitdir ( $file );
shift @dirs;
$file = join ( "::", @dirs );
return if $file eq 'Cookbook'; #Skip non-backend modules in D::S namespace
$found{ $file } = 1;
};
File::Find::find ( $collector, @possible_locations );
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AnyData.pm view on Meta::CPAN
For further support, please use comp.lang.perl.modules
=head1 ACKNOWLEDGEMENTS
Special thanks to Andy Duncan, Tom Lowery, Randal Schwartz, Michel Rodriguez, Jochen Wiedmann, Tim Bunce, Alligator Descartes, Mathew Persico, Chris Nandor, Malcom Cook and to many others on the DBI mailing lists and the clp* newsgroups.
=head1 AUTHOR & COPYRIGHT
Jeff Zucker <jeff@vpservices.com>
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AnyEvent/FCGI/Request.pm view on Meta::CPAN
local $CGI::Q = new CGI::Stateless;
$request->respond(
'Hello, ' . (CGI::param('name') || 'anonymous'),
'Content-Type' => 'text/html; charset=utf8',
'Set-Cookie' => 'cookie_a=1; path=/',
'Set-Cookie' => 'cookie_b=2; path=/',
);
}
);
AnyEvent->loop;
view all matches for this distribution
view release on metacpan or search on metacpan
t/10_determined_test.t view on Meta::CPAN
}
}
print "HTTP/1.0 200 OK\r\n";
print "Content-Type: text/html\r\n";
print "Set-Cookie: test=abc; path=/\r\n";
print "\r\n";
print <<__HTML__;
<html>
<head>
<title>Test Web Page</title>
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AnyEvent/HTTP/LWP/UserAgent.pm view on Meta::CPAN
$code == &HTTP::Status::RC_TEMPORARY_REDIRECT)
{
my $referral = $request->clone;
# These headers should never be forwarded
$referral->remove_header('Host', 'Cookie');
if ($referral->header('Referer') &&
$request->uri->scheme eq 'https' &&
$referral->uri->scheme eq 'http')
{
view all matches for this distribution
view release on metacpan or search on metacpan
the request will fail with an error.
=item headers => hashref
The request headers to use. Currently, C<http_request> may provide its own
C<Host:>, C<Content-Length:>, C<Connection:> and C<Cookie:> headers and
will provide defaults at least for C<TE:>, C<Referer:> and C<User-Agent:>
(this can be suppressed by using C<undef> for these headers in which case
they won't be sent at all).
You really should provide your own C<User-Agent:> header value that is
of the cookie jar.
Note that this cookie implementation is not meant to be complete. If
you want complete cookie management you have to do that on your
own. C<cookie_jar> is meant as a quick fix to get most cookie-using sites
working. Cookies are a privacy disaster, do not use them unless required
to.
When cookie processing is enabled, the C<Cookie:> and C<Set-Cookie:>
headers will be set and handled by this module, otherwise they will be
left untouched.
=item tls_ctx => $scheme | $tls_ctx
Takes a POSIX timestamp (seconds since the epoch) and formats it as a HTTP
Date (RFC 2616).
=item $timestamp = AnyEvent::HTTP::parse_date $date
Takes a HTTP Date (RFC 2616) or a Cookie date (netscape cookie spec) or a
bunch of minor variations of those, and returns the corresponding POSIX
timestamp, or C<undef> if the date cannot be parsed.
=item $AnyEvent::HTTP::MAX_RECURSE
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AnyEvent/HTTPD/CookiePatch.pm view on Meta::CPAN
package AnyEvent::HTTPD::CookiePatch;
use 5.006;
use strict;
use warnings FATAL => 'all';
=head1 NAME
AnyEvent::HTTPD::CookiePatch -
Patch of AnyEvent::HTTPD for cookie support
=head1 VERSION
Version 0.01
lib/AnyEvent/HTTPD/CookiePatch.pm view on Meta::CPAN
=head1 SYNOPSIS
# by module injection
use AnyEvent::HTTPD::CookiePatch qw(inject);
# or by inheritance
use AnyEvent::HTTPD::CookiePatch;
my $httpd = AnyEvent::HTTPD->new( request_class => 'AnyEvent::HTTPD::CookiePatch' );
# and then in your handler
sub {
my($httpd, $req) = @_;
lib/AnyEvent/HTTPD/CookiePatch.pm view on Meta::CPAN
Set the cookie
=head2 $req->{_set_cookie}
The response header field Set-Cookie's value
=cut
use AnyEvent::HTTPD::SendMultiHeaderPatch;
our @ISA = 'AnyEvent::HTTPD::Request';
lib/AnyEvent/HTTPD/CookiePatch.pm view on Meta::CPAN
}
=head1 CAVEATS
This module use module L<AnyEvent::HTTPD::SendMultiHeaderPatch> (a hack)
for sending multiple Set-Cookie response header.
=head1 AUTHOR
Cindy Wang (CindyLinz)
lib/AnyEvent/HTTPD/CookiePatch.pm view on Meta::CPAN
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=cut
1; # End of AnyEvent::HTTPD::CookiePatch
view all matches for this distribution
view release on metacpan or search on metacpan
t/lib/RPC/ExtDirect/Test/Util/AnyEvent.pm view on Meta::CPAN
}
if ( exists $config->{'-cgi_env'} ) {
my $cookie = $config->{'-cgi_env'}->{HTTP_COOKIE};
$req->header('Cookie', $cookie) if $cookie;
}
my $cfg_obj = RPC::ExtDirect::Config->new(
debug_serialize => 1,
%$config,
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AnyEvent/HTTPD/SendMultiHeaderPatch.pm view on Meta::CPAN
sub {
my($httpd, $req) = @_;
# ...
$req->respond(
200, 'OK', {
'Set-Cookie' => "a=123; path=/; domain=.example.com\0b=456; path=/; domain=.example.com"
}, "Set the cookies"
);
}
# Or use the added util function header_add in AnyEvent::HTTPD::Util.
lib/AnyEvent/HTTPD/SendMultiHeaderPatch.pm view on Meta::CPAN
sub {
my($httpd, $req) = @_;
# ...
my %header;
header_add(\%header, 'Set-Cookie', 'a=123; path=/; domain=.example.com');
header_add(\%header, 'Set-Cookie', 'b=456; path=/; domain=.example.com');
$req->respond(200, 'OK', \%header, "Set the cookies");
}
# There also introduced another util function header_gets in AnyEvent::HTTPD::Util,
# to extract multiple values in the header
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AnyEvent/MSN.pm view on Meta::CPAN
<wsse:Password>%s</wsse:Password>
<wsse:Username>%s</wsse:Username>
</wsse:UsernameToken>
</wsse:Security>
<ps:AuthInfo Id="PPAuthInfo" xmlns:ps="http://schemas.microsoft.com/Passport/SoapServices/PPCRL">
<ps:Cookies></ps:Cookies>
<ps:UIVersion>1</ps:UIVersion>
<ps:HostingApp>{7108E71A-9926-4FCB-BCC9-9A9D3F32E423}</ps:HostingApp>
<ps:BinaryVersion>4</ps:BinaryVersion>
<ps:RequestParams>AQAAAAIAAABsYwQAAAAxMDMz</ps:RequestParams>
</ps:AuthInfo>
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AnyEvent/Mattermost.pm view on Meta::CPAN
my $headers = [
'Content-Type' => 'application/json',
'X-Requested-With' => 'XMLHttpRequest',
];
# initial_load is fine with just the Cookie, other endpoints like channels/
# require Authorization. We'll just always include both to be sure.
if (exists $self->{'token'}) {
push(@{$headers},
'Cookie' => 'MMAUTHTOKEN=' . $self->{'token'},
'Authorization' => 'Bearer ' . $self->{'token'},
);
}
return $headers;
view all matches for this distribution
view release on metacpan or search on metacpan
t/43-loopback-yada.t view on Meta::CPAN
is(0 + $result, 0, 'got CURLE_OK');
ok(!$self->has_error, "libcurl message: '$result'");
like(${$self->data}, qr{\bContent-Type:\s*application/json\b}ix, 'got data: ' . ${$self->data});
like(${$self->data}, qr{\bUser-Agent\s*:\s*\Q$ua_string\E\b}sx, 'got User-Agent tag');
like(${$self->data}, qr{\bCookie\s*:\s*time=\d+\b}sx, 'got Cookie tag');
},
)
});
}
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AnyEvent/UserAgent.pm view on Meta::CPAN
# (punytan@gmail.com): http://github.com/punytan/AnyEvent-HTTP-Simple
use Moo;
use AnyEvent::HTTP ();
use HTTP::Cookies ();
use HTTP::Request ();
use HTTP::Request::Common ();
use HTTP::Response ();
use namespace::clean;
lib/AnyEvent/UserAgent.pm view on Meta::CPAN
our $VERSION = '0.09';
has agent => (is => 'rw', default => sub { $AnyEvent::HTTP::USERAGENT . ' AnyEvent-UserAgent/' . $VERSION });
has cookie_jar => (is => 'rw', default => sub { HTTP::Cookies->new });
has max_redirects => (is => 'rw', default => sub { 5 });
has inactivity_timeout => (is => 'rw', default => sub { 20 });
lib/AnyEvent/UserAgent.pm view on Meta::CPAN
delete($hdrs->{URL});
if (defined($hdrs->{HTTPVersion})) {
$res->protocol('HTTP/' . delete($hdrs->{HTTPVersion}));
}
if (my $hdr = $hdrs->{'set-cookie'}) {
# Split comma-concatenated "Set-Cookie" values.
# Based on RFC 6265, section 4.1.1.
local @_ = split(/,([\w.!"'%\$&*+-^`]+=)/, ',' . $hdr);
shift();
my @val;
push(@val, join('', shift(), shift())) while @_;
lib/AnyEvent/UserAgent.pm view on Meta::CPAN
$cv->recv();
=head1 DESCRIPTION
AnyEvent::UserAgent is a OO-wrapper around L<AnyEvent::HTTP> with cookies
support by L<HTTP::Cookies>. Also request callback receives response as
L<HTTP::Response> object.
=head1 ATTRIBUTES
=head2 agent
lib/AnyEvent/UserAgent.pm view on Meta::CPAN
=head2 cookie_jar
The cookie jar object to use. The only requirement is that the cookie jar object
must implement the C<extract_cookies($req)> and C<add_cookie_header($res)>
methods. These methods will then be invoked by the user agent as requests are
sent and responses are received. Normally this will be a L<HTTP::Cookies> object
or some subclass. Default cookie jar is the L<HTTP::Cookies> object.
=head2 inactivity_timeout
Maximum time in seconds in which connection can be inactive before getting
closed. Default timeout value is C<20>. Setting the value to C<0> will allow
lib/AnyEvent/UserAgent.pm view on Meta::CPAN
C<persistent => 0> option to the C<AnyEvent::UserAgent> constructor otherwise
some requests might fail.
=head1 SEE ALSO
L<AnyEvent::HTTP>, L<HTTP::Cookies>, L<HTTP::Request::Common>, L<HTTP::Request>,
L<HTTP::Response>.
=head1 SUPPORT
=over 4
view all matches for this distribution
view release on metacpan or search on metacpan
WebDriver.pm view on Meta::CPAN
caller until the result is available (using L<AnyEvent> condvars), so must
not be called from an event loop callback - see L<EVENT BASED API> for an
alternative.
The method names are pretty much taken directly from the W3C WebDriver
specification, e.g. the request documented in the "Get All Cookies"
section is implemented via the C<get_all_cookies> method.
The order is the same as in the WebDriver draft at the time of this
writing, and only minimal massaging is done to request parameters and
results.
view all matches for this distribution
view release on metacpan or search on metacpan
@Objects %Register %XSLT
$ServerID $ServerPID $SrandPid
$CompileErrorSize $CacheSize @CompileChecksumKeys
%ScriptLanguages $ShareDir $INCDir $AbsoluteFileMatch
$QuickStartTime
$SessionCookieName
$LoadModPerl
$ModPerl2
);
# other common modules load now, these are optional though, so we do not error upon failure
map { eval "sub $_ { shift->{$_} }" } @Objects;
# use regexp directly, not sub for speed
$AbsoluteFileMatch = '^(/|[a-zA-Z]:)';
$CacheSize = 1024*1024*10;
$SessionCookieName = 'session-id';
# ServerID creates a unique identifier for the server
srand();
$ServerID = substr(md5_hex($$.rand().time().(-M('..')||'').(-M('/')||'')), 0, 16);
$ServerPID = $$;
PerlSetVar StateSerializer Data::Dumper
=head2 Sessions
=item CookiePath
URL root that client responds to by sending the session cookie.
If your asp application falls under the server url "/asp",
then you would set this variable to /asp. This then allows
you to run different applications on the same server, with
different user sessions for each application.
PerlSetVar CookiePath /
=item CookieDomain
Default 0, this NON-PORTABLE configuration will allow sessions to span
multiple web sites that match the same domain root. This is useful if
your web sites are hosted on the same machine and can share the same
StateDir configuration, and you want to shared the $Session data
across web sites. Whatever this is set to, that will add a
; domain=$CookieDomain
part to the Set-Cookie: header set for the session-id cookie.
PerlSetVar CookieDomain .your.global.domain
=item SessionTimeout
Default 20 minutes, when a user's session has been inactive for this
period of time, the Session_OnEnd event is run, if defined, for
because there is a performance hit associated with this
count tracking, so it is disabled by default.
PerlSetVar SessionCount 1
=head2 Cookieless Sessions
=item SessionQueryParse
default 0, if true, will automatically parse the $Session
session id into the query string of each local URL found in the
=item CgiHeaders
default 0. When true, script output that looks like HTTP / CGI
headers, will be added to the HTTP headers of the request.
So you could add:
Set-Cookie: test=message
<html>...
to the top of your script, and all the headers preceding a newline
will be added as if with a call to $Response->AddHeader(). This
functionality is here for compatibility with raw cgi scripts,
=item $Response->Clear()
Erases buffered ASP output.
=item $Response->Cookies($name, [$key,] $value)
Sets the key or attribute of cookie with name $name to the value $value.
If $key is not defined, the Value of the cookie is set.
ASP CookiePath is assumed to be / in these examples.
$Response->Cookies('name', 'value');
--> Set-Cookie: name=value; path=/
$Response->Cookies("Test", "data1", "test value");
$Response->Cookies("Test", "data2", "more test");
$Response->Cookies(
"Test", "Expires",
&HTTP::Date::time2str(time+86400)
);
$Response->Cookies("Test", "Secure", 1);
$Response->Cookies("Test", "Path", "/");
$Response->Cookies("Test", "Domain", "host.com");
--> Set-Cookie:Test=data1=test%20value&data2=more%20test; \
expires=Fri, 23 Apr 1999 07:19:52 GMT; \
path=/; domain=host.com; secure
The latter use of $key in the cookies not only sets cookie attributes
such as Expires, but also treats the cookie as a hash of key value pairs
which can later be accesses by
$Request->Cookies('Test', 'data1');
$Request->Cookies('Test', 'data2');
Because this is perl, you can (NOT PORTABLE) reference the cookies
directly through hash notation. The same 5 commands above could be compressed to:
$Response->{Cookies}{Test} =
{
Secure => 1,
Value =>
{
data1 => 'test value',
and the first command would be:
# you don't need to use hash notation when you are only setting
# a simple value
$Response->{Cookies}{'Test Name'} = 'Test Value';
I prefer the hash notation for cookies, as this looks nice, and is
quite perlish. It is here to stay. The Cookie() routine is
very complex and does its best to allow access to the
underlying hash structure of the data. This is the best emulation
I could write trying to match the Collections functionality of
cookies in IIS ASP.
For more information on Cookies, please go to the source at
http://home.netscape.com/newsref/std/cookie_spec.html
=item $Response->Debug(@args)
API Extension. If the Debug config option is set greater than 0,
=item $Request->ClientCertificate()
Not implemented.
=item $Request->Cookies($name [,$key])
Returns the value of the Cookie with name $name. If a $key is
specified, then a lookup will be done on the cookie as if it were
a query string. So, a cookie set by:
Set-Cookie: test=data1=1&data2=2
would have a value of 2 returned by $Request->Cookies('test','data2').
If no name is specified, a hash will be returned of cookie names
as keys and cookie values as values. If the cookie value is a query string,
it will automatically be parsed, and the value will be a hash reference to
these values.
When in doubt, try it out. Remember that unless you set the Expires
attribute of a cookie with $Response->Cookies('cookie', 'Expires', $xyz),
the cookies that you set will only last until you close your browser,
so you may find your self opening & closing your browser a lot when
debugging cookies.
For more information on cookies in ASP, please read $Response->Cookies()
=item $Request->FileUpload($form_field, $key)
API extension. The FileUpload interface to file upload data is
stabilized. The internal representation of the file uploads
will do the trick :)
=head1 SESSIONS
Cookies are used by default for user $Session support ( see OBJECTS ).
In order to track a web user and associate server side data
with that client, the web server sets, and the web client returns
a 32 byte session id identifier cookie. This implementation
is very secure and may be used in secure HTTPS transactions,
and made stronger with SecureSession, HTTPOnlySession and
Because of these reasons, web users will sometimes turn off
their cookies, rendering normal ASP session implementations
powerless, resulting in a new $Session generated every request.
This is not good for ASP style sessions.
=head2 Cookieless Sessions
*** See WARNING Below ***
So we now have more ways to track sessions with the
SessionQuery* CONFIG settings, that allow a web developer
$Session
$Request->FileUpload *
$Request->FileUpload('upload_file') *
$Request->Form
$Request->QueryString
$Request->Cookies
$Response->Cookies
$Response->Cookies('some_cookie')
* FileUpload API Extensions
And as such may be used with the following syntax, as compared
with the Apache::ASP native calls. Please note the native Apache::ASP
## Collection->Item($name)
[C] print $Request->QueryString->Item('message'), "<br>\n\n";
[N] print $Request->{QueryString}{'message'}, "<br>\n\n";
## Working with Cookies
[C] $Response->SetProperty('Cookies', 'Testing', 'Extra');
[C] $Response->SetProperty('Cookies', 'Testing', {'Path' => '/'});
[C] print $Request->Cookies(Testing) . "<br>\n";
[N] $Response->{Cookies}{Testing} = {Value => Extra, Path => '/'};
[N] print $Request->{Cookies}{Testing} . "<br>\n";
Several incompatibilities exist between PerlScript and Apache::ASP:
> Collection->{Count} property has not been implemented.
> VBScript dates may not be used for Expires property of cookies.
=head2 Books
mod_perl "Eagle" Book
http://www.modperl.com
mod_perl Developer's Cookbook
http://www.modperlcookbook.org
Programming the Perl DBI
http://www.oreilly.com/catalog/perldbi/
+ preloaded CGI for file uploads in the mod_perl environment
- When XSLT config is set, $Response->Redirect() should work now
Thanks to Marcus Zoller for pointing problem out
+ Added CookieDomain setting, documented, and added test to cover
it in t/cookies.t . Setting suggested by Uwe Riehm, who nicely
submitted some code for this.
=item $VERSION = 2.53; $DATE="04/10/2003"
+ removed useless Apache::ASP::Collection::DESTROY
+ removed useless Apache::ASP::Server::DESTROY
+ removed useless Apache::ASP::GlobalASA::DESTROY
+ removed useless Apache::ASP::Response::DESTROY
- Default path for $Response->{Cookies} was from CookiePath
config, but this was incorrect as CookiePath config is only
for $Session cookie, so now path for $Response->{Cookies}
defaults to /
- Fixed bug where global.asa events would get undefined with
StatINC and GlobalPackage set when the GlobalPackage library
changed & get reloaded.
and destination filter. Added ./site/eg/filter.filter example
to demonstrate these abilities.
+ Use $r->err_headers_out->add Apache::Table API for cookies
now instead of $r->cgi_header_out. Added t/cookies.t test to
cover new code path as well as general $Response->Cookies API.
Also make cookies headers sorted by cookie and dictionary key
while building headers for repeatable behavior, this latter was
to facilitate testing.
- fixed $Server->Mail error_log output when failing to connect
-StatINC setting with Apache::ASP->Loader() works again.
This makes StatINC & StatINCMatch settings viable
for production & development use when the system has
very many modules.
-Cookieless session support with configs like SessionQueryParse
and SessionQuery now work for URLs with frags in them
like http://localhost?arg=value#frag
+@rv = $Response->Include() now works where there are
multiple return values from an include like:
+ > mode for opening lock files, not >>, since its faster
+$Response->Flush() fixed, by giving $| = 1 perl hint
to $r->print() and the rest of the perl sub.
+$Response->{Cookies}{cookie_name}{Expires} = -86400 * 300;
works so negative relative time may be used to expire cookies.
+Count() + Key() Collection class API implementations
+Added editors/aasp.vim VIM syntax file for Apache::ASP,
UniquePackages has scripts compiled into separate perl packages,
so they may define subs with the same name, w/o fear of overlap.
Under this settings, scripts will not be able to share globals.
-Secure field for cookies in $Response->Cookies() must be TRUE to
force cookie to be secure. Before, it just had to be defined,
which gave wrong behavior for Secure => 0.
+$Response->{IsClientConnected} set to one by default. Will
work out a real value when I upgrade to apache 1.3.6. This
=item $VERSION = 0.09; $DATE="04/22/1999";
+Updated Makefile.PL optional modules output for CGI & DB_File
+Improved docs on $Response->Cookies() and $Request->Cookies()
+Added PERFORMANCE doc to main README, and added sub section
on precompiling scripts with Apache::ASP->Loader()
+Naming of CompileIncludes switched over to DynamicIncludes
+Command line cgi/asp script takes various options, and allows execution
of multiple asp scripts at one time. This script should be used for
command line debugging. This is also the beginning of building
a static site from asp scripts with the -b option, suppressing headers.
+$Response->AddHeader('Set-Cookie') works for multiple cookies.
-$Response->Cookies('foo', '0') works, was dropping 0 because of boolean test
-Fixed up some config doc errors.
=item $VERSION = 0.07; $DATE="01/20/1999";
internal state could be lost.
--State file locking. Corruption worries, and loss of data no more.
+CGI header support, developer can use CGI.pm for *output*, or just print()
: print "Set-Cookie: test=cookie\n", and things will just work
: use CGI.pm for output
: utilizes $r->send_cgi_header(), thanks Doug!
+Improved Cookie implementation, more flexible and complete
- Domain cookie key now works
: Expire times now taken from time(), and relative time in sec
: Request->Cookies() reading more flexible, with wantarray()
on hash cookie values, %hash = $Request->Cookie('test');
-make test module naming correction, was t.pm, now T.pm for Unix
+POD / README cleanup, formatting and HTML friendly.
+Installation 'make test' now works
+ActiveX objects on Win32 implemented with $Server->CreateObject()
+Cookies implemented: $Response->Cookies() & $Request->Cookies()
-Fixed $Response object API, converting some methods to object members.
Deprecated methods, but backwards compatible.
+Improved error messaging, debug output
view all matches for this distribution
view release on metacpan or search on metacpan
Server/t/lib/Apache/test.pm view on Meta::CPAN
return $net::callback_hooks{PERL_TABLE_API};
}
},
);
for (qw(Apache::Cookie Apache::Request)) {
$really_have{$_} = $really_have{'Apache::Table'};
}
sub have_module {
my $mod = shift;
Server/t/lib/Apache/test.pm view on Meta::CPAN
values are all 1.
=head1 EXAMPLES
No good examples yet. Example submissions are welcome. In the meantime, see
L<http://forum.swarthmore.edu/~ken/modules/Apache-AuthCookie/> , which
I'm retrofitting to use Apache::test.
=head1 TO DO
The MM_test method doesn't try to be very smart, it just writes the
text that seems to work in my configuration. I am morally against
using the 'make' command for installing Perl modules (though of course
I do it anyway), so I haven't looked into this very much. Send bug
reports or better (patches).
I've got lots of code in my Apache::AuthCookie module (etc.) that
assists in actually making the queries of the running server. I plan
to add that to this module, but first I need to compare what's already
here that does the same stuff.
=head1 KUDOS
view all matches for this distribution
view release on metacpan or search on metacpan
lib/Apache/AppSamurai.pm view on Meta::CPAN
$MP = 1;
}
}
# Non-mod_perl includes
use CGI::Cookie;
use URI;
use Time::HiRes qw(usleep);
use Apache::AppSamurai::Util qw(CreateSessionAuthKey CheckSidFormat
HashPass HashAny ComputeSessionId
lib/Apache/AppSamurai.pm view on Meta::CPAN
# be shared between all processes serving an auth_name
use Apache::AppSamurai::Tracker;
### START Apache::AuthSession based methods
# The following lower case methods are directly based on Apache::AuthCookie, or
# are required AuthCookie methods (like authen_cred() and authen_ses_key())
# Note - ($$) syntax, used in mod_perl 1 to induce calling the handler as
# an object, has been eliminated in mod_perl 2. Each handler method called
# directly from Apache must be wrapped to support mod_perl 1 and mod_perl 2
# calls. (Just explaining the mess before you have to read it.)
lib/Apache/AppSamurai.pm view on Meta::CPAN
return DECLINED unless $auth_type and $auth_name;
my $cookie_name = $self->cookie_name($r);
my ($cookie) = $r->headers_in->{'Cookie'} =~ /$cookie_name=([^;]+)/;
if (!$cookie && $r->dir_config("${auth_name}Keysource")) {
# Try to get key text using alternate method then compute the key.
# FetchKeysource returns '' if no custom source is configured, in
# which case the cookie should have been previously set, so non-zero
# output is required.
lib/Apache/AppSamurai.pm view on Meta::CPAN
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;
}
# Set request cache options (no-cache unless specifically told to cache)
lib/Apache/AppSamurai.pm view on Meta::CPAN
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");
$self->Log($r, ('debug', "remove_cookie(): removed_cookie \"$cookie_name\""));
}
# Convert current POST request to GET
lib/Apache/AppSamurai.pm view on Meta::CPAN
$destination = $ar->param("destination");
} else {
# Someday something slick could hold the URL, then cut through
# to it. Someday. Today we die.
$self->Log($r, ('warn', "No key 'destination' found in form data"));
$r->subprocess_env('AuthCookieReason', 'no_cookie');
return $auth_type->login_form($r);
}
# Check form nonce and signature
if (defined($ar->param("nonce")) and defined($ar->param("sig"))) {
unless (($nonce = CheckSidFormat($ar->param("nonce"))) and
($sig = CheckSidFormat($ar->param("sig")))) {
$self->Log($r, ('warn', "Missing/invalid form nonce or sig"));
$r->subprocess_env('AuthCookieReason', 'no_cookie');
$r->err_headers_out->{'Location'} = $self->URLErrorCode($destination, 'bad_credentials');
$r->status(REDIRECT);
return REDIRECT;
}
$serverkey = $self->GetServerKey($r) or die("FATAL: Could not fetch valid server key\n");
# Now check!
unless ($sig eq ComputeSessionId($nonce, $serverkey)) {
# Failed!
$self->Log($r, ('warn', "Bad signature on posted form (Possible scripted attack)"));
$r->subprocess_env('AuthCookieReason', 'no_cookie');
$r->err_headers_out->{'Location'} = $self->URLErrorCode($destination, 'bad_credentials');
$r->status(REDIRECT);
return REDIRECT;
}
} else {
# Failed!
$self->Log($r, ('warn', "Missing NONCE and/or SIG in posted form (Possible scripted attack)"));
$r->subprocess_env('AuthCookieReason', 'no_cookie');
$r->err_headers_out->{'Location'} = $self->URLErrorCode($destination, 'bad_credentials');
$r->status(REDIRECT);
return REDIRECT;
}
lib/Apache/AppSamurai.pm view on Meta::CPAN
# point. (Avoids having the LOGIN URL show up in the browser window)
$r->err_headers_out->{'Location'} = $self->URLErrorCode($destination, 'bad_credentials');
$r->status(REDIRECT);
return REDIRECT;
# Handle this ol' style - XXX remove?
#$r->subprocess_env('AuthCookieReason', 'bad_credentials');
#$r->uri($destination);
#return $auth_type->login_form($r);
}
# Special version of login that handles Basic Auth login instead of form
lib/Apache/AppSamurai.pm view on Meta::CPAN
my $r = shift;
my $auth_name = $r->auth_name;
my $redirect = shift || "";
my ($sid, %sess, $sessconfig, $username, $alterlist);
# Get the Cookie header. If there is a session key for this realm, strip
# off everything but the value of the cookie.
my $cookie_name = $self->cookie_name($r);
my ($key) = $r->headers_in->{'Cookie'} =~ /$cookie_name=([^;]+)/;
# Try custom keysource if no cookie is present and Keysource is configured
if (!$key && $auth_name && $r->dir_config("${auth_name}Keysource")) {
# Pull in key text
$key = $self->FetchKeysource($r);
lib/Apache/AppSamurai.pm view on Meta::CPAN
# Load alterlist
$alterlist = $self->AlterlistLoad(\%sess);
# Re-apply passback cookies to which were cleared and backdated
# after session creation. (This clears the passback cookies)
if (defined($alterlist->{cookie})) {
$self->AlterlistPassBackCookie($alterlist, $r);
}
$self->DestroySession($r, \%sess);
untie(%sess);
$self->Log($r, ('notice', "LOGOUT: username=\"$username\", session=\"$sid\", reason=logout"));
lib/Apache/AppSamurai.pm view on Meta::CPAN
unless ($auth_name) {
$r->log_reason("AuthName not set, AuthType=$self", $r->uri);
return HTTP_INTERNAL_SERVER_ERROR;
}
# Get the Cookie header. If there is a session key for this realm, strip
# off everything but the value of the cookie.
my $cookie_name = $self->cookie_name($r);
my ($ses_key_cookie) = ($r->headers_in->{"Cookie"} || "") =~ /$cookie_name=([^;]+)/;
$foundcookie = 0;
if ($ses_key_cookie) {
# If cookie found and not "", set $foundcookie to note auth key source
$foundcookie = 1;
lib/Apache/AppSamurai.pm view on Meta::CPAN
my $auth_name = $r->auth_name;
if (my $p3p = $r->dir_config("${auth_name}P3P")) {
$r->err_headers_out->{'P3P'} = $p3p;
}
$r->err_headers_out->add("Set-Cookie" => $cookie);
}
# Convert cookie store to header ready string
sub cookie_string {
my $self = shift;
lib/Apache/AppSamurai.pm view on Meta::CPAN
my ($self, $r) = @_;
my $auth_name = $r->auth_name;
my $key = "";
my $allcook = ($r->headers_in->{"Cookie"} || "");
my $cookie_name = $self->cookie_name($r);
($key) = $allcook =~ /(?:^|\s)$cookie_name=([^;]*)/;
# Try custom keysource if no cookie is present and Keysource is configured
if (!$key && $auth_name && $r->dir_config("${auth_name}Keysource")) {
lib/Apache/AppSamurai.pm view on Meta::CPAN
if ($reason) {
# Oh no! They gave us a reason... It's ON! (well, off)
# Remove passback and session cookies first
if (defined($alterlist->{cookie})) {
$self->AlterlistPassBackCookie($alterlist, $r);
}
$self->remove_cookie($r);
$self->handle_cache($r);
lib/Apache/AppSamurai.pm view on Meta::CPAN
# If serving basic auth, return undef instead of triggering login form
if ($r->auth_type =~ /^basic$/i) {
return undef;
} else {
# Use Apache::AuthCookie based custom_errors feature, which will
# call back into our custom_errors() method. (expired_cookie
# applies as an acceptable error for all of these cases.)
return('login', 'expired_cookie');
}
}
lib/Apache/AppSamurai.pm view on Meta::CPAN
# What was that? Die out.
die "custom_errors(): Invalid code passed to custom_errors: \"$code\"";
}
}
## END Apache::AuthCookie based methods
# Everything past this point is not an overridden/modified Apache::AuthCookie
# function.
# Taking a request, try to get the <AuthName>AuthMethods list for the resource
sub GetAuthMethods {
my ($self, $r) = @_;
lib/Apache/AppSamurai.pm view on Meta::CPAN
$sess{'Expire'} = $sessconfig->{Expire};
}
# Apply passback cookies to response, and pull in updated alterlist
if (defined($alterlist->{cookie})) {
$alterlist = $self->AlterlistPassBackCookie($alterlist, $r);
}
# If present, save Authorization header to detect future changes,
# then prepend an alterlist rule to delete the header to prevent
# pass though to the backend server. (If needed, a separate
lib/Apache/AppSamurai.pm view on Meta::CPAN
# ------
# @{$self->{alterlist}->{cookie}} - One or more cookie transforms, with the
# syntax:
# ACTION:NAME:VALUE
# ACTION - add, replace, delete, or passback
# NAME - Cookie name (or regex match for delete)
# VALUE - New value of cookie, or regex filter for delete action (Prefix
# pattern with ! for negation)
#
# Note - delete rules with optional value match pattern will delete only values
# of a multi-value cookie that match the value pattern
lib/Apache/AppSamurai.pm view on Meta::CPAN
$self->Log($r, ('debug', "AlterlistApply(): Applied alterlist for header"));
}
if (defined($alterlist->{cookie})) {
# Run through cookies (saving off alter count)
$self->AlterlistApplyCookie($alterlist, $r);
$self->Log($r, ('debug', "AlterlistApply(): Applied alterlist for cookie"));
}
return $alterlist;
}
lib/Apache/AppSamurai.pm view on Meta::CPAN
return $alterlist;
}
# Apply alterlist rules to request cookies.
# Note - Does not handle "passback" cookie. Use AlterlistPassBackCookie() to
# retrieve and clear passback cookies)
sub AlterlistApplyCookie {
my ($self, $alterlist, $r) = @_;
(defined($alterlist->{cookie})) || (return 0);
my ($t, %c, $cl, $act, $key, $val, $tk, $tv, @ta, @td);
my $alterred = 0;
# Grab any cookies any put into a hash of CGI::Cookies, or just make an
# empty cookie hash for now.
%c = CGI::Cookie->fetch($r);
(%c) || (%c = ());
# Build \n deliminated lookup string to fast match against
$cl = "\n" . join("\n", keys(%c)) . "\n";
foreach $t (@{$alterlist->{cookie}}) {
# Note - : or = allowed between NAME and VALUE to make life easier
($t =~ /^(add|replace|rep|delete|del|passback|set):([\w\d\-]+)(?:\:|\=)(.*?)$/i) || (($self->Log($r, ('debug', "AlterlistApplyCookie(): Skipping illegal cookie transform \"$t\""))) && (next));
$act = $1;
$key = $2;
$val = $3;
if ($act =~ /^passback|set$/) {
# passback not handled in this method
next;
} elsif ($act =~ /^add$/) {
# Blindly add the cookie
@ta = split('&', $val);
# Add a new CGI::Cookie to the hash
$c{$key} = new CGI::Cookie(-name => $key, -value => \@ta);
# Log obscured value
$self->Log($r, ('debug', "AlterlistApplyCookie(): COOKIE ADD: $key=" . XHalf($val)));
$alterred++;
} else {
# Replace and delete allow for regex cookie name matches
while ($cl =~ /($key)/igm) {
# Update
lib/Apache/AppSamurai.pm view on Meta::CPAN
# Blindly delete then add the cookie back with new value
# Save old value for log
$tv = join('&', $c{$tk}->value);;
delete($c{$tk});
@ta = split('&', $val);
$c{$tk} = new CGI::Cookie(-name => $tk, -value => \@ta);
# Log obscured values
$self->Log($r, ('debug', "AlterlistApplyCookie(): COOKIE REPLACE: $tk: " . XHalf($tv) . " -> " . XHalf($val)));
$alterred++;
} elsif ($act =~ /^delete|del$/) {
# Check for extra content match
if ($val) {
@ta = ();
lib/Apache/AppSamurai.pm view on Meta::CPAN
# Some values left not deleted, so set those back
$c{$tk}->value(\@ta);
$tv = join('&', @td);
# Log obscured value
$self->Log($r, ('debug', "AlterlistApplyCookie(): COOKIE DELETE PARTIAL: $tk=" . XHalf($tv)));
} else {
# Nothing left inside. KILL!
delete($c{$tk});
$tv = join('&', @td);
# Obscure values for logging
$tv =~ s/([^X])[\w\d]/${1}X/gs;
$self->Log($r, ('debug', "AlterlistApplyCookie(): COOKIE DELETE FULL: $tk=$tv"));
}
} else {
# Kill Em All
$tv = $c{$key}->value;
delete($c{$key});
# Obscure values for logging
$tv =~ s/([^X])[\w\d]/${1}X/gs;
$self->Log($r, ('debug', "AlterlistApplyCookie(): COOKIE DELETE FULL: $key=$tv"));
$alterred++;
}
}
}
}
}
# Unset, then add cookies to header if changes were made
if ($alterred) {
$r->headers_in->unset('Cookie');
$t = '';
foreach $tk (keys %c) {
# Cookie to list in string form.
$t .= $c{$tk}->name . "=" . join('&', $c{$tk}->value) . "; ";
}
# Kill trailing '; '
$t =~ s/\; $//s;
# Ship it
$r->headers_in->add('Cookie' => $t);
}
return $alterlist;
}
lib/Apache/AppSamurai.pm view on Meta::CPAN
# The only time this can occur is upon login/redirect. The purpose of passback
# cookies is to set the same cookies in the browser as they would have set
# if they were connecting directly to the backend server(s).
#
# The return should be used to update the alterlist. When
# AlterlistPassBackCookie is applied again, it will UNSET the passback cookies.
# This should be done on logout.
sub AlterlistPassBackCookie() {
my ($self, $alterlist, $r) = @_;
(defined($alterlist->{cookie})) || (return 0);
my ($t, $key, $val, $opt, $tdomain, $tpath, $texpire);
my @ct = ();
lib/Apache/AppSamurai.pm view on Meta::CPAN
$key = $2;
$val = $3;
$opt = $4;
$tdomain = $tpath = $texpire = '';
# Unlike AlterlistApplyCookie which just needs to parse name and
# value, the PassBack cookies are Set-Cookie items which may
# have options. Also, only process the last cookie value if
# a multi-value cookie is passed
# Add a new CGI::Cookie to the hash
$c{$key} = new CGI::Cookie(-name => $key,
-value => $val,
);
# Set further options (only Expires and Path currently passed through)
foreach $t (split(';', $opt)) {
if ($t =~ /^\s*expires=([\w\d \:\;\-,]+)\s*$/) {
lib/Apache/AppSamurai.pm view on Meta::CPAN
}
if (!$r->dir_config("${auth_name}Secure") || ($r->dir_config("${auth_name}Secure") == 1)) {
$c{$key}->secure(1);
}
$r->err_headers_out->add('Set-Cookie' => $c{$key});
# Clean up and log
$t = $c{$key};
$t =~ /($key\s*\=\s*)(.*?)(;|$)/;
$self->Log($r, ('debug', "AlterlistPassBackCookie(): COOKIE PASSBACK: " . $1 . XHalf($2) . $3));
# Save an empty/expired cookie so next call to AlterlistPassBackCookie
# with this alterlist will unset the cookie
$c{$key}->value('');
$c{$key}->expires('Thu, 1-Jan-1970 00:00:00 GMT');
push(@ct, "passback:" . $c{$key});
}
lib/Apache/AppSamurai.pm view on Meta::CPAN
}
# Append an error code to the list of query args in a given URL. (Used to
# pass friendly error messages to users in external redirects. (Note that
# AuthCookie used subprocess_env() to pass that info, but since that will only
# work in the same main request, it won't pass into an external redirect.)
sub URLErrorCode {
my $self = shift;
my $uri = (shift) || (return undef);
my $ecode = (shift) || ('');
lib/Apache/AppSamurai.pm view on Meta::CPAN
session is created and a session authentication cookie is passed back to the
browser. Only authenticated and authorized requests are proxied through
to the backend server.
Apache::AppSamurai is based on, and includes some code from,
L<Apache::AuthCookie|Apache::AuthCookie>.
Upon that core is added a full authentication and session handling framework.
(No coding required.) Features include:
=over 4
lib/Apache/AppSamurai.pm view on Meta::CPAN
(Default: 0)
Set to 1 to send debugging output to the Apache logs. (Note - you must have
a log configured to catch errors, including debug level errors, to see the
output.)
=head3 I<CookieName> C<NAME>
(Default:AUTHTYPE_AUTHNAME)
The name of the session cookie to send to the browser.
=head3 I<LoginScript> C<PATH>
lib/Apache/AppSamurai.pm view on Meta::CPAN
# Load the main module and define configuration options for the
# "Example" auth_name
PerlModule Apache::AppSamurai
PerlSetVar ExampleDebug 0
PerlSetVar ExampleCookieName MmmmCookies
PerlSetVar ExamplePath /
PerlSetVar ExampleLoginScript /login.pl
# Defaults to All by may also be Any
#PerlSetVar ExampleSatisty All
lib/Apache/AppSamurai.pm view on Meta::CPAN
# Always send Basic authentication header to backend server
PerlSetVar ExampleAuthBasicKeepAuth 1
# Capture cookies from AuthBasic login and set in client browser
PerlSetVar ExampleAuthBasicPassBackCookies 1
# Abort the check unless the "realm" returned by the server matches
PerlSetVar ExampleAuthBasicRequireRealm "blah.bleh.blech"
# Pass the named header directly through to the AuthBasic server
lib/Apache/AppSamurai.pm view on Meta::CPAN
Other features may be more difficult to add. (Apache::AppSamurai could
use some refactoring.)
Interface and utility methods are not documented at this time. Please
consult the code, and also the L<Apache::AuthCookie|Apache::AuthCookie>
documentation.
=head1 FILES
=over 4
lib/Apache/AppSamurai.pm view on Meta::CPAN
=back
=head1 ACKNOWLEDGEMENTS
AppSamurai.pm (the main Apache::AppSamurai module), contains some code
from Apache::AuthCookie, which was developed by Ken Williams and others.
The included Apache::AuthCookie code is under the same licenses as Perl
and under the following copyright:
Copyright (c) 2000 Ken Williams. All rights reserved.
=head1 COPYRIGHT & LICENSE
view all matches for this distribution
view release on metacpan or search on metacpan
lib/Apache/Auth/AuthMemCookie.pm view on Meta::CPAN
package Apache::Auth::AuthMemCookie;
use strict;
use CGI::Cookie ();
use Apache2::RequestUtil;
use Apache2::RequestIO;
use APR::Table;
use Apache2::RequestRec;
use Apache2::Const -compile => qw(OK REDIRECT FORBIDDEN AUTH_REQUIRED);
lib/Apache/Auth/AuthMemCookie.pm view on Meta::CPAN
use Data::Dumper;
=pod
=head1 B<Apache::Auth::AuthMemCookie - Authenticate using a memcache stored session>
=head2 B<Module Usage>
=over
This module is used to take the place of Apache2 authmemcookie primarily for the use
of integration with simpleSAMLphp L<http://rnd.feide.no/simplesamlphp> .
Alias /simplesaml /home/piers/git/public/simplesamlphp/www
perlModule Apache::Auth::AuthMemCookie
ErrorDocument 401 "/simplesaml/authmemcookie.php"
PerlRequire /path/to/authmemcookie/tools/startup.pl
perlModule Apache::Auth::AuthMemCookie
# Prompt for authentication:
<Location /location_to_protect>
AuthType Cookie
AuthName "My Service"
Require valid-user
PerlAuthenHandler Apache::Auth::AuthMemCookie::authen_handler
PerlSetVar AuthMemCookie "AuthMemCookie"
PerlSetVar AuthMemServers "127.0.0.1:11211, /var/sock/memcached"
PerlSetVar AuthMemAttrsInHeaders 1 # if you want to set headers instead of ENV vars
PerlSetVar AuthMemDebug 1 # if you want to debug
</Location>
lib/Apache/Auth/AuthMemCookie.pm view on Meta::CPAN
$r->headers_in->unset('UserName');
$r->headers_in->unset('X_REMOTE_USER');
$r->headers_in->unset('X-Remote-User');
# what is our cookie called
my $cookie_name = $r->dir_config("AuthMemCookie") ? $r->dir_config("AuthMemCookie") : 'AuthMemCookie';
mydebug("Headers in: ".Dumper($r->headers_in));
# sort out our memcached connection
unless ($memd) {
my @memd_servers = split /\s*(?:,)\s*/, ($r->dir_config("AuthMemServers") ? $r->dir_config("AuthMemServers") : '127.0.0.1:11211, /var/sock/memcached');
lib/Apache/Auth/AuthMemCookie.pm view on Meta::CPAN
};
mydebug("memcache servers: ".Dumper(\@memd_servers));
}
# get and process the cookies
my $cookies = $r->headers_in->get('Cookie');
$cookies = parse CGI::Cookie($cookies);
my $auth_cookie = exists $cookies->{$cookie_name} ? $cookies->{$cookie_name}->value() : "";
# do we have the AuthMemCookie?
unless ($auth_cookie) {
mydebug("AuthMemCookie does not exist ($cookie_name) -> forcing login");
return Apache2::Const::AUTH_REQUIRED;
}
my $val = $memd->get($auth_cookie);
# Do we have a valid Memcached session?
unless ($val) {
mydebug("Memcached session not found for AuthMemCookie ($cookie_name): $auth_cookie");
return Apache2::Const::AUTH_REQUIRED;
}
mydebug("AuthMemCookie value: $val");
# we found a valid MemCache session so push it into the environment and let them go
my %vars = map { my ($k, $v) = split(/=/, $_, 2); $k => $v } (split(/\r\n/, $val));
# should the values be set in the headers
view all matches for this distribution
view release on metacpan or search on metacpan
lib/Apache/AuthCAS.pm view on Meta::CPAN
# default
$NUM_PROXY_TICKETS = $DEFAULT_NUM_PROXY_TICKETS;
}
# session settings
if ($tmp = $r->dir_config("CASSessionCookieName")) {
$SESSION_COOKIE_NAME = $tmp;
Apache->warn("$$: CAS: initialize(): setting CASSessionCookieName to $SESSION_COOKIE_NAME") unless ($LOG_LEVEL < $LOG_INFO);
} else {
# default
$SESSION_COOKIE_NAME = $DEFAULT_SESSION_COOKIE_NAME;
}
if ($tmp = $r->dir_config("CASSessionCookieDomain")) {
$SESSION_COOKIE_DOMAIN = $tmp;
Apache->warn("$$: CAS: initialize(): setting CASSessionCookieDomain to $SESSION_COOKIE_DOMAIN") unless ($LOG_LEVEL < $LOG_INFO);
} else {
# default
$SESSION_COOKIE_DOMAIN = $DEFAULT_SESSION_COOKIE_DOMAIN;
}
if ($tmp = $r->dir_config("CASSessionTimeout")) {
lib/Apache/AuthCAS.pm view on Meta::CPAN
$r->push_handlers(PerlResponseHandler => \&send_proxysuccess);
} # else treat this as a normal authentication request
# determine any session cookies/session id we may have recieved
my ($cookie, $sid) = ("", "");
if (!defined($cookie = $r->header_in('Cookie'))) {
# if we don't have a session cookie, the user can't be valid
Apache->warn("$$: CAS: authenticate(): no session cookie found") unless ($LOG_LEVEL < $LOG_DEBUG);
my $service;
if ($SERVICE eq "") {
lib/Apache/AuthCAS.pm view on Meta::CPAN
if ($SESSION_COOKIE_DOMAIN ne "") {
$cookie .= ";domain=.$SESSION_COOKIE_DOMAIN";
}
# send the cookie to the browser
$r->header_out("Set-Cookie" => $cookie);
# in case we redirect (considered an "error")
$r->err_header_out("Set-Cookie" => $cookie);
} else {
Apache->warn("$$: CAS: authenticate(): no valid session id or ticket") unless ($LOG_LEVEL < $LOG_DEBUG);
return $self->redirect_login($r);
}
lib/Apache/AuthCAS.pm view on Meta::CPAN
PerlSetVar CASDatabaseHost "db.somedomain.com"
PerlSetVar CASDatabasePort "5432"
PerlSetVar CASDatabaseDriver "Pg"
PerlSetVar CASDatabaseUser "dbuser"
PerlSetVar CASDatabasePass "dbpass"
PerlSetVar CASSessionCookieName "APACHECAS"
PerlSetVar CASSessionTimeout "1800"
PerlSetVar CASLogLevel "0"
PerlSetVar CASRemoveTicket "false"
require valid-user
lib/Apache/AuthCAS.pm view on Meta::CPAN
PerlSetVar CASDatabaseHost "db.somedomain.com"
PerlSetVar CASDatabasePort "5432"
PerlSetVar CASDatabaseDriver "Pg"
PerlSetVar CASDatabaseUser "dbuser"
PerlSetVar CASDatabasePass "dbpass"
PerlSetVar CASSessionCookieName "APACHECAS"
PerlSetVar CASSessionTimeout "1800"
PerlSetVar CASLogLevel "0"
PerlSetVar CASRemoveTicket "false"
require valid-user
lib/Apache/AuthCAS.pm view on Meta::CPAN
# whether we should perform a redirect, stripping the service ticket
# once we have already created a session for the client
PerlSetVar CASRemoveTicket "true"
# the name of the cookie that will be used for sessions
PerlSetVar CASSessionCookieName "APACHECAS"
# the max time before a session expires (in seconds)
PerlSetVar CASSessionTimeout "1800"
# not currently able to override through Apache configuration:
view all matches for this distribution
view release on metacpan or search on metacpan
lib/Apache/AuthCookie.pm view on Meta::CPAN
package Apache::AuthCookie;
$Apache::AuthCookie::VERSION = '3.32';
# ABSTRACT: Perl Authentication and Authorization via cookies
use strict;
use Carp;
use mod_perl qw(1.07 StackedHandlers MethodHandlers Authen Authz);
use Apache::Constants qw(:common M_GET FORBIDDEN OK REDIRECT);
use Apache::AuthCookie::Params;
use Apache::AuthCookie::Util qw(is_blank is_local_destination);
use Apache::Util qw(escape_uri);
use Apache::URI;
use Encode ();
lib/Apache/AuthCookie.pm view on Meta::CPAN
my ($self, $r) = @_;
# only check if user is not already set
return DECLINED unless is_blank($r->connection->user);
my $debug = $r->dir_config("AuthCookieDebug") || 0;
my ($auth_type, $auth_name) = ($r->auth_type, $r->auth_name);
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) {
lib/Apache/AuthCookie.pm view on Meta::CPAN
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;
}
lib/Apache/AuthCookie.pm view on Meta::CPAN
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;
my $args = $self->params($r);
lib/Apache/AuthCookie.pm view on Meta::CPAN
sub params {
my ($self, $r) = @_;
return Apache::AuthCookie::Params->new($r);
}
sub login ($$) {
my ($self, $r) = @_;
my $debug = $r->dir_config("AuthCookieDebug") || 0;
my ($auth_type, $auth_name) = ($r->auth_type, $r->auth_name);
my $params = $self->params($r);
lib/Apache/AuthCookie.pm view on Meta::CPAN
$destination = $default_destination;
$r->log_error("destination set to $destination");
}
else {
$r->log_error("No key 'destination' found in form data");
$r->subprocess_env('AuthCookieReason', 'no_cookie');
return $auth_type->login_form;
}
}
if ($r->dir_config("${auth_name}EnforceLocalDestination")) {
lib/Apache/AuthCookie.pm view on Meta::CPAN
$destination = $default_destination;
$r->log_error("destination changed to $destination");
}
else {
$r->log_error("Returning login form: non local destination: $destination");
$r->subprocess_env('AuthCookieReason', 'no_cookie');
return $auth_type->login_form($r);
}
}
}
lib/Apache/AuthCookie.pm view on Meta::CPAN
# Exchange the credentials for a session key.
my $ses_key = $self->authen_cred($r, @credentials);
unless ($ses_key) {
$r->log_error("Bad credentials") if $debug >= 2;
$r->subprocess_env('AuthCookieReason', 'bad_credentials');
$r->uri($self->untaint_destination($destination));
return $auth_type->login_form;
}
if ($debug >= 2) {
lib/Apache/AuthCookie.pm view on Meta::CPAN
sub untaint_destination {
my ($self, $dest) = @_;
return Apache::AuthCookie::Util::escape_destination($dest);
}
sub logout($$) {
my ($self, $r) = @_;
my $debug = $r->dir_config("AuthCookieDebug") || 0;
$self->remove_cookie;
$self->handle_cache;
lib/Apache/AuthCookie.pm view on Meta::CPAN
sub authenticate ($$) {
my ($auth_type, $r) = @_;
my $auth_user;
my $debug = $r->dir_config("AuthCookieDebug") || 0;
$r->log_error("auth_type " . $auth_type) if ($debug >= 3);
unless ($r->is_initial_req) {
if (defined $r->prev) {
lib/Apache/AuthCookie.pm view on Meta::CPAN
unless ($auth_name) {
$r->log_reason("AuthName not set, AuthType=$auth_type", $r->uri);
return SERVER_ERROR;
}
# Get the Cookie header. If there is a session key for this realm, strip
# off everything but the value of the cookie.
my $cookie_name = $auth_type->cookie_name($r);
my ($ses_key_cookie) =
($r->header_in("Cookie") || "") =~ /$cookie_name=([^;]+)/;
$ses_key_cookie = "" unless defined($ses_key_cookie);
$r->log_error("ses_key_cookie " . $ses_key_cookie) if ($debug >= 1);
$r->log_error("uri " . $r->uri) if ($debug >= 2);
lib/Apache/AuthCookie.pm view on Meta::CPAN
# There was a session key set, but it's invalid for some reason. So,
# remove it from the client now so when the credential data is posted
# we act just like it's a new session starting.
$auth_type->remove_cookie;
$r->subprocess_env('AuthCookieReason', 'bad_cookie');
}
}
else {
$r->subprocess_env('AuthCookieReason', 'no_cookie');
}
# They aren't authenticated, and they tried to get a protected
# document. Send them the authen form.
return $auth_type->login_form;
lib/Apache/AuthCookie.pm view on Meta::CPAN
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;
}
lib/Apache/AuthCookie.pm view on Meta::CPAN
}
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) {
lib/Apache/AuthCookie.pm view on Meta::CPAN
);
# add P3P header if user has configured it.
$self->send_p3p($r);
$r->err_headers_out->add("Set-Cookie" => $cookie);
}
sub send_p3p {
my ($self, $r) = @_;
lib/Apache/AuthCookie.pm view on Meta::CPAN
my $string = sprintf '%s=%s', @p{ 'key', 'value' };
my $auth_name = $r->auth_name;
if (my $expires = $p{expires} || $r->dir_config("${auth_name}Expires")) {
$expires = Apache::AuthCookie::Util::expires($expires);
$string .= "; expires=$expires";
}
$string .= '; path=' . ($self->get_cookie_path($r) || '/');
lib/Apache/AuthCookie.pm view on Meta::CPAN
sub key {
my $self = shift;
my $r = Apache->request;
my $allcook = ($r->header_in("Cookie") || "");
my $cookie_name = $self->cookie_name($r);
return ($allcook =~ /(?:^|\s)$cookie_name=([^;]*)/)[0];
}
lib/Apache/AuthCookie.pm view on Meta::CPAN
=encoding UTF-8
=head1 NAME
Apache::AuthCookie - Perl Authentication and Authorization via cookies
=head1 VERSION
version 3.32
lib/Apache/AuthCookie.pm view on Meta::CPAN
Make sure your mod_perl is at least 1.24, with StackedHandlers,
MethodHandlers, Authen, and Authz compiled in.
# 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
lib/Apache/AuthCookie.pm view on Meta::CPAN
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
lib/Apache/AuthCookie.pm view on Meta::CPAN
# 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>
=head1 DESCRIPTION
B<Apache::AuthCookie> allows you to intercept a user's first
unauthenticated access to a protected document. The user will be
presented with a custom form where they can enter authentication
credentials. The credentials are posted to the server where AuthCookie
verifies them and returns a session key.
The session key is returned to the user's browser as a cookie. As a
cookie, the browser will pass the session key on every subsequent
accesses. AuthCookie will verify the session key and re-authenticate
the user.
All you have to do is write a custom module that inherits from
AuthCookie. Your module is a class which implements two methods:
=over 4
=item C<authen_cred()>
lib/Apache/AuthCookie.pm view on Meta::CPAN
ID will be fed to C<$r-E<gt>connection-E<gt>user()> to set Apache's
idea of who's logged in.
=back
By using AuthCookie versus Apache's built-in AuthBasic you can design
your own authentication system. There are several benefits.
=over 4
=item 1.
lib/Apache/AuthCookie.pm view on Meta::CPAN
problem of AuthBasic.
=item 3.
AuthBasic dialog boxes are ugly. You can design your own HTML login
forms when you use AuthCookie.
=item 4.
You can specify the domain of a cookie using PerlSetVar commands. For
instance, if your AuthName is C<WhatEver>, you can put the command
lib/Apache/AuthCookie.pm view on Meta::CPAN
into your server setup file and your access cookies will span all
hosts ending in C<.yourhost.com>.
=item 5.
You can optionally specify the name of your cookie using the C<CookieName>
directive. For instance, if your AuthName is C<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.
=item 6.
By default users must satisfy ALL of the C<require> directives. If you
lib/Apache/AuthCookie.pm view on Meta::CPAN
=back
This is the flow of the authentication handler, less the details of the
redirects. Two REDIRECT'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.
(-----------------------) +---------------------------------+
( 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 | |
lib/Apache/AuthCookie.pm view on Meta::CPAN
/ \ | |
/ \ 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 )--------------+
lib/Apache/AuthCookie.pm view on Meta::CPAN
=head1 METHODS
=head2 authen_cred($r, @credentials)
You must define this method yourself in your subclass of
C<Apache::AuthCookie>. Its job is to create the session key that will
be preserved in the user's cookie. The arguments passed to it are:
sub authen_cred ($$\@) {
my $self = shift; # Package name (same as AuthName directive)
my $r = shift; # Apache request object
lib/Apache/AuthCookie.pm view on Meta::CPAN
doesn't tamper with the session key. More info in the Eagle book.
=head2 authen_ses_key($r, $session_key)
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) = @_;
lib/Apache/AuthCookie.pm view on Meta::CPAN
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)
lib/Apache/AuthCookie.pm view on Meta::CPAN
=item *
key
The Cookie name
=item *
value
the Cookie value
=item *
expires (optional)
When the cookie expires. See L<Apache::AuthCookie::Util/expires()>. Uses C<${auth_name}Expires> if not given.
=back
All other cookie settings come from C<PerlSetVar> settings.
lib/Apache/AuthCookie.pm view on Meta::CPAN
Returns the value of C<PerlSetVar ${auth_name}Path>.
=head1 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).
lib/Apache/AuthCookie.pm view on Meta::CPAN
get passed to your authen_cred() method.
=item 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 C<$r-E<gt>prev-E<gt>uri>.
See the login.pl script in t/eg/.
=back
lib/Apache/AuthCookie.pm view on Meta::CPAN
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, B<AuthCookie> will set
C<$r-E<gt>subprocess_env('AuthCookieReason')> to one of the following values.
=over 4
=item I<no_cookie>
lib/Apache/AuthCookie.pm view on Meta::CPAN
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>.
lib/Apache/AuthCookie.pm view on Meta::CPAN
=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
lib/Apache/AuthCookie.pm view on Meta::CPAN
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
lib/Apache/AuthCookie.pm view on Meta::CPAN
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));
view all matches for this distribution
view release on metacpan or search on metacpan
AuthCookieDBI.pm view on Meta::CPAN
#===============================================================================
#
# $Id: AuthCookieDBI.pm,v 1.22.2.4 2007/02/03 19:22:24 matisse Exp $
#
# Apache::AuthCookieDBI
#
# An AuthCookie module backed by a DBI database.
#
# Copyright (C) 2000-2003 SF Interactive.
#
# Author: Jacob Davies <jacob@well.com>
#
AuthCookieDBI.pm view on Meta::CPAN
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
#===============================================================================
package Apache::AuthCookieDBI;
use strict;
use warnings;
use 5.004_04;
our $VERSION = 2.10;
use Apache;
use Apache::AuthCookie;
use Apache::DBI;
use Apache::Constants;
use Apache::File;
use Digest::MD5 qw( md5_hex );
use Date::Calc qw( Today_and_Now Add_Delta_DHMS );
# Also uses Crypt::CBC if you're using encrypted cookies.
use base qw( Apache::AuthCookie );
my $EMPTY_STRING = q{};
#===============================================================================
# F U N C T I O N D E C L A R A T I O N S
AuthCookieDBI.pm view on Meta::CPAN
# P E R L D O C
#===============================================================================
=head1 NAME
Apache::AuthCookieDBI - An AuthCookie module backed by a DBI database.
=head1 VERSION
$Revision: 1.22.2.4 $
AuthCookieDBI.pm view on Meta::CPAN
# This PerlSetVar MUST precede the PerlModule line because the
# key is read in a BEGIN block when the module is loaded.
PerlSetVar WhatEverDBI_SecretKeyFile /etc/httpd/acme.com.key
PerlModule Apache::AuthCookieDBI
PerlSetVar WhatEverPath /
PerlSetVar WhatEverLoginScript /login.pl
# Optional, to share tickets between servers.
PerlSetVar WhatEverDomain .domain.com
AuthCookieDBI.pm view on Meta::CPAN
PerlSetVar WhatEverDBI_GroupField "grp"
PerlSetVar WhatEverDBI_GroupUserField "user"
PerlSetVar WhatEverDBI_EncryptionType "none"
PerlSetVar WhatEverDBI_SessionLifetime 00-24-00-00
# Protected by AuthCookieDBI.
<Directory /www/domain.com/authcookiedbi>
AuthType Apache::AuthCookieDBI
AuthName WhatEver
PerlAuthenHandler Apache::AuthCookieDBI->authenticate
PerlAuthzHandler Apache::AuthCookieDBI->authorize
require valid-user
# or you can require users:
require user jacob
# You can optionally require groups.
require group system
</Directory>
# Login location.
<Files LOGIN>
AuthType Apache::AuthCookieDBI
AuthName WhatEver
SetHandler perl-script
PerlHandler Apache::AuthCookieDBI->login
</Files>
=head1 DESCRIPTION
This module is an authentication handler that uses the basic mechanism provided
by Apache::AuthCookie with a DBI database for ticket-based protection. It
is based on two tokens being provided, a username and password, which can
be any strings (there are no illegal characters for either). The username is
used to set the remote user as if Basic Authentication was used.
On an attempt to access a protected location without a valid cookie being
AuthCookieDBI.pm view on Meta::CPAN
sub _log_not_set {
my ( $r, $variable ) = @_;
my $auth_name = $r->auth_name;
return $r->log_error(
"Apache::AuthCookieDBI: $variable not set for auth realm
$auth_name", $r->uri
);
}
#-------------------------------------------------------------------------------
AuthCookieDBI.pm view on Meta::CPAN
AuthName is PrivateBankingSystem they will look like:
PerlSetVar PrivateBankingSystemDBI_DSN "DBI:mysql:database=banking"
See also L<Apache::Authcookie> for the directives required for any kind
of Apache::AuthCookie-based authentication system.
In the following descriptions, replace "WhatEver" with your particular
AuthName. The available configuration directives are as follows:
=over 4
AuthCookieDBI.pm view on Meta::CPAN
}
=item C<WhatEverDBI_SessionLifetime>
How long tickets are good for after being issued. Note that presently
Apache::AuthCookie does not set a client-side expire time, which means that
most clients will only keep the cookie until the user quits the browser.
However, if you wish to force people to log in again sooner than that, set
this value. This can be 'forever' or a life time specified as:
DD-hh-mm-ss -- Days, hours, minute and seconds to live.
AuthCookieDBI.pm view on Meta::CPAN
my $auth_name = $r->auth_name;
( $user, $password ) = _defined_or_empty( $user, $password );
if ( !length $user ) {
$r->log_reason(
"Apache::AuthCookieDBI: no username supplied for auth realm $auth_name",
$r->uri
);
return;
}
if ( !length $password ) {
$r->log_reason(
"Apache::AuthCookieDBI: no password supplied for auth realm $auth_name",
$r->uri
);
return;
}
AuthCookieDBI.pm view on Meta::CPAN
# get the crypted password from the users database for this user.
my $dbh = DBI->connect( $c{DBI_DSN}, $c{DBI_user}, $c{DBI_password} );
unless ( defined $dbh ) {
$r->log_reason(
"Apache::AuthCookieDBI: couldn't connect to $c{ DBI_DSN } for auth realm $auth_name",
$r->uri
);
return;
}
my $sth = $dbh->prepare( <<"EOS" );
AuthCookieDBI.pm view on Meta::CPAN
EOS
$sth->execute($user);
my ($crypted_password) = $sth->fetchrow_array;
unless ( defined $crypted_password ) {
$r->log_reason(
"Apache::AuthCookieDBI: couldn't select password from $c{ DBI_DSN }, $c{ DBI_userstable }, $c{ DBI_userfield } for user $user for auth realm $auth_name",
$r->uri
);
return;
}
# now return unless the passwords match.
if ( lc $c{DBI_crypttype} eq 'none' ) {
unless ( $password eq $crypted_password ) {
$r->log_reason(
"Apache::AuthCookieDBI: plaintext passwords didn't match for user $user for auth realm $auth_name",
$r->uri
);
return;
}
}
elsif ( lc $c{DBI_crypttype} eq 'crypt' ) {
my $salt = substr $crypted_password, 0, 2;
unless ( crypt( $password, $salt ) eq $crypted_password ) {
$r->log_reason(
"Apache::AuthCookieDBI: crypted passwords didn't match for user $user for auth realm $auth_name",
$r->uri
);
return;
}
}
elsif ( lc $c{DBI_crypttype} eq 'md5' ) {
unless ( md5_hex($password) eq $crypted_password ) {
$r->log_reason(
"Apache::AuthCookieDBI: MD5 passwords didn't match for user $user for auth realm $auth_name",
$r->uri
);
return;
}
}
AuthCookieDBI.pm view on Meta::CPAN
# Now we calculate the hash of this and the secret key and then
# calculate the hash of *that* and the secret key again.
my $secret_key = $SECRET_KEYS{$auth_name};
unless ( defined $secret_key ) {
$r->log_reason(
"Apache::AuthCookieDBI: didn't have the secret key for auth realm $auth_name",
$r->uri
);
return;
}
my $hash =
AuthCookieDBI.pm view on Meta::CPAN
# Get the secret key.
my $secret_key = $SECRET_KEYS{$auth_name};
unless ( defined $secret_key ) {
$r->log_reason(
"Apache::AuthCookieDBI: didn't have the secret key from for auth realm $auth_name",
$r->uri
);
return;
}
AuthCookieDBI.pm view on Meta::CPAN
else {
# Check that this looks like an encrypted hex-encoded string.
unless ( $encrypted_session_key =~ /^[0-9a-fA-F]+$/ ) {
$r->log_reason(
"Apache::AuthCookieDBI: encrypted session key $encrypted_session_key doesn't look like it's properly hex-encoded for auth realm $auth_name",
$r->uri
);
return;
}
AuthCookieDBI.pm view on Meta::CPAN
$cipher = $CIPHERS{"blowfish_pp:$auth_name"} ||=
Crypt::CBC->new( $secret_key, 'Blowfish_PP' );
}
else {
$r->log_reason(
"Apache::AuthCookieDBI: unknown encryption type $c{ DBI_encryptiontype } for auth realm $auth_name",
$r->uri
);
return;
}
$session_key = $cipher->decrypt_hex($encrypted_session_key);
AuthCookieDBI.pm view on Meta::CPAN
_defined_or_empty( $enc_user, $issue_time, $expire_time, $supplied_hash );
# Let's check that we got passed sensible values in the cookie.
unless ( $enc_user =~ /^[a-zA-Z0-9_\%]+$/ ) {
$r->log_reason(
"Apache::AuthCookieDBI: bad percent-encoded user $enc_user recovered from session ticket for auth_realm $auth_name",
$r->uri
);
return;
}
# decode the user
my $user = _percent_decode($enc_user);
unless ( $issue_time =~ /^\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}$/ ) {
$r->log_reason(
"Apache::AuthCookieDBI: bad issue time $issue_time recovered from ticket for user $user for auth_realm $auth_name",
$r->uri
);
return;
}
unless ( $expire_time =~ /^\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}$/ ) {
$r->log_reason(
"Apache::AuthCookieDBI: bad expire time $expire_time recovered from ticket for user $user for auth_realm $auth_name",
$r->uri
);
return;
}
unless ( $supplied_hash =~ /^[0-9a-fA-F]{32}$/ ) {
$r->log_reason(
"Apache::AuthCookieDBI: bad hash $supplied_hash recovered from ticket for user $user for auth_realm $auth_name",
$r->uri
);
return;
}
AuthCookieDBI.pm view on Meta::CPAN
);
# Compare it to the hash they gave us.
unless ( $hash eq $supplied_hash ) {
$r->log_reason(
"Apache::AuthCookieDBI: hash in cookie did not match calculated hash of contents for user $user for auth realm $auth_name",
$r->uri
);
return;
}
# Check that their session hasn't timed out.
if ( _now_year_month_day_hour_minute_second gt $expire_time ) {
$r->log_reason(
"Apache:AuthCookieDBI: expire time $expire_time has passed for user $user for auth realm $auth_name",
$r->uri
);
return;
}
AuthCookieDBI.pm view on Meta::CPAN
# See if we have a row in the groups table for this user/group.
my $dbh = DBI->connect( $c{DBI_DSN}, $c{DBI_user}, $c{DBI_password} );
unless ( defined $dbh ) {
$r->log_reason(
"Apache::AuthCookieDBI: couldn't connect to $c{ DBI_DSN } for auth realm $auth_name",
$r->uri
);
return;
}
AuthCookieDBI.pm view on Meta::CPAN
foreach my $group (@groups) {
$sth->execute( $group, $user );
return OK if ( $sth->fetchrow_array );
}
$r->log_reason(
"Apache::AuthCookieDBI: user $user was not a member of any of the required groups @groups for auth realm $auth_name",
$r->uri
);
return FORBIDDEN;
}
AuthCookieDBI.pm view on Meta::CPAN
<jacob@well.com>
=head1 SEE ALSO
Apache::AuthCookie(1)
=cut
view all matches for this distribution
view release on metacpan or search on metacpan
AuthCookie.pm view on Meta::CPAN
package Apache::AuthCookie;
use strict;
use Carp;
use CGI::Util ();
use mod_perl qw(1.07 StackedHandlers MethodHandlers Authen Authz);
use Apache::Constants qw(:common M_GET M_POST FORBIDDEN REDIRECT);
use vars qw($VERSION);
# $Id: AuthCookie.pm,v 2.16 2001/06/01 15:50:27 mschout Exp $
$VERSION = '3.00';
sub recognize_user ($$) {
my ($self, $r) = @_;
my $debug = $r->dir_config("AuthCookieDebug") || 0;
my ($auth_type, $auth_name) = ($r->auth_type, $r->auth_name);
return unless $auth_type && $auth_name;
return unless $r->header_in('Cookie');
my ($cookie) = $r->header_in('Cookie') =~ /${auth_type}_${auth_name}=([^;]+)/;
$r->log_error("cookie ${auth_type}_${auth_name} is $cookie") if $debug >= 2;
return unless $cookie;
if (my ($user) = $auth_type->authen_ses_key($r, $cookie)) {
$r->log_error("user is $user") if $debug >= 2;
AuthCookie.pm view on Meta::CPAN
}
sub login ($$) {
my ($self, $r) = @_;
my $debug = $r->dir_config("AuthCookieDebug") || 0;
my ($auth_type, $auth_name) = ($r->auth_type, $r->auth_name);
my %args = $r->method eq 'POST' ? $r->content : $r->args;
unless (exists $args{'destination'}) {
$r->log_error("No key 'destination' found in posted data");
AuthCookie.pm view on Meta::CPAN
return REDIRECT;
}
sub logout($$) {
my ($self,$r) = @_;
my $debug = $r->dir_config("AuthCookieDebug") || 0;
my ($auth_type, $auth_name) = ($r->auth_type, $r->auth_name);
# Send the Set-Cookie header to expire the auth cookie.
my $str = $self->cookie_string( request => $r,
key => "$auth_type\_$auth_name",
value => '',
expires => 'Mon, 21-May-1971 00:00:00 GMT' );
$r->err_headers_out->add("Set-Cookie" => "$str");
$r->log_error("set_cookie " . $r->err_header_out("Set-Cookie")) if $debug >= 2;
unless ($r->dir_config("${auth_name}Cache")) {
$r->no_cache(1);
$r->err_header_out("Pragma" => "no-cache");
}
AuthCookie.pm view on Meta::CPAN
}
sub authenticate ($$) {
my ($auth_type, $r) = @_;
my ($authen_script, $auth_user);
my $debug = $r->dir_config("AuthCookieDebug") || 0;
$r->log_error("auth_type " . $auth_type) if ($debug >= 3);
return OK unless $r->is_initial_req; # Only authenticate the first internal request
if ($r->auth_type ne $auth_type) {
AuthCookie.pm view on Meta::CPAN
unless ($auth_name) {
$r->log_reason("AuthName not set, AuthType=$auth_type", $r->uri);
return SERVER_ERROR;
}
# Get the Cookie header. If there is a session key for this realm, strip
# off everything but the value of the cookie.
my ($ses_key_cookie) = ($r->header_in("Cookie") || "") =~ /$auth_type\_$auth_name=([^;]+)/;
$ses_key_cookie = "" unless defined($ses_key_cookie);
$r->log_error("ses_key_cookie " . $ses_key_cookie) if ($debug >= 1);
$r->log_error("uri " . $r->uri) if ($debug >= 2);
AuthCookie.pm view on Meta::CPAN
request => $r,
key => "$auth_type\_$auth_name",
value => '',
expires => 'Mon, 21-May-1971 00:00:00 GMT'
);
$r->err_headers_out->add("Set-Cookie" => "$str");
$r->log_error("set_cookie " . $r->err_header_out("Set-Cookie")) if $debug >= 2;
#$r->subprocess_env('AuthCookieReason', 'Bad Cookie');
# Instead of 'Bad Cookie', lets return something more useful.
# $ses_key_cookie has a unique value if ERROR, but undef if ! ERROR.
$r->subprocess_env('AuthCookieReason', $ses_key_cookie) if $ses_key_cookie =~ /ERROR/;
$r->subprocess_env('AuthCookieReason', 'ERROR! Your session has expired, or your login does not have the proper access level for this webpage.') if $ses_key_cookie !~ /ERROR/;
}
} else {
#$r->subprocess_env('AuthCookieReason', 'no_cookie');
# Instead of 'no_cookie, let's return something more useful.
$r->subprocess_env('AuthCookieReason', 'Please enter your user name and password.');
}
# They aren't authenticated, and they tried to get a protected
# document. Send them the authen form.
return $auth_type->login_form;
AuthCookie.pm view on Meta::CPAN
return FORBIDDEN;
}
sub authorize ($$) {
my ($auth_type, $r) = @_;
my $debug = $r->dir_config("AuthCookieDebug") || 0;
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 " .
AuthCookie.pm view on Meta::CPAN
last;
}
#return $forbidden ? FORBIDDEN : OK;
# Was returning generic Apache FORBIDDEN here. We want to return to login.pl with error message.
$r->subprocess_env('AuthCookieReason', 'ERROR! Your login does not have the proper permission for this webpage.') if $forbidden;
$r->log_error("AuthCookie, ERROR! Login not in list for this directory using require user ...") if $forbidden;
return $auth_type->login_form if $forbidden;
return OK;
}
AuthCookie.pm view on Meta::CPAN
my ($auth_type, $auth_name) = ($r->auth_type, $r->auth_name);
my $cookie = $self->cookie_string( request => $r,
key => "$auth_type\_$auth_name",
value => $ses_key );
$r->err_header_out("Set-Cookie" => $cookie);
}
sub cookie_string {
my $self = shift;
AuthCookie.pm view on Meta::CPAN
sub key {
my $self = shift;
my $r = Apache->request;
my $allcook = ($r->header_in("Cookie") || "");
my ($type, $name) = ($r->auth_type, $r->auth_name);
return ($allcook =~ /(?:^|\s)${type}_$name=([^;]*)/)[0];
}
1;
__END__
=head1 NAME
Apache::AuthCookie - Perl Authentication and Authorization via cookies
=head1 SYNOPSIS
Make sure your mod_perl is at least 1.24, with StackedHandlers,
MethodHandlers, Authen, and Authz compiled in.
# In httpd.conf or .htaccess:
PerlModule Sample::AuthCookieHandler
PerlSetVar WhatEverPath /
PerlSetVar WhatEverLoginScript /login.pl
# The following line is optional - it allows you to set the domain
# scope of your cookie. Default is the current domain.
AuthCookie.pm view on Meta::CPAN
# Use this to make your cookies persistent (+2 hours here)
PerlSetVar WhatEverExpires +2h
# These documents require user to be logged in.
<Location /protected>
AuthType Sample::AuthCookieHandler
AuthName WhatEver
PerlAuthenHandler Sample::AuthCookieHandler->authenticate
PerlAuthzHandler Sample::AuthCookieHandler->authorize
require valid-user
</Location>
# These documents don't require logging in, but allow it.
<FilesMatch "\.ok$">
AuthType Sample::AuthCookieHandler
AuthName WhatEver
PerlFixupHandler Sample::AuthCookieHandler->recognize_user
</FilesMatch>
# This is the action of the login.pl script above.
<Files LOGIN>
AuthType Sample::AuthCookieHandler
AuthName WhatEver
SetHandler perl-script
PerlHandler Sample::AuthCookieHandler->login
</Files>
=head1 DESCRIPTION
B<Apache::AuthCookie> allows you to intercept a user's first
unauthenticated access to a protected document. The user will be
presented with a custom form where they can enter authentication
credentials. The credentials are posted to the server where AuthCookie
verifies them and returns a session key.
The session key is returned to the user's browser as a cookie. As a
cookie, the browser will pass the session key on every subsequent
accesses. AuthCookie will verify the session key and re-authenticate
the user.
All you have to do is write a custom module that inherits from
AuthCookie. Your module is a class which implements two methods:
=over 4
=item C<authen_cred()>
AuthCookie.pm view on Meta::CPAN
ID will be fed to C<$r-E<gt>connection-E<gt>user()> to set Apache's
idea of who's logged in.
=back
By using AuthCookie versus Apache's built-in AuthBasic you can design
your own authentication system. There are several benefits.
=over 4
=item 1.
AuthCookie.pm view on Meta::CPAN
problem of AuthBasic.
=item 3.
AuthBasic dialog boxes are ugly. You can design your own HTML login
forms when you use AuthCookie.
=item 4.
You can specify the domain of a cookie using PerlSetVar commands. For
instance, if your AuthName is C<WhatEver>, you can put the command
AuthCookie.pm view on Meta::CPAN
=back
This is the flow of the authentication handler, less the details of the
redirects. Two REDIRECT'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.
=for html
<PRE>
(-----------------------) +---------------------------------+
( 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 | |
AuthCookie.pm view on Meta::CPAN
/ \ | |
/ \ 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 \ ^
| sucsesive 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 )--------------+
AuthCookie.pm view on Meta::CPAN
=for html
</PRE>
=head1 METHODS
C<Apache::AuthCookie> has several methods you should know about. Here
is the documentation for each. =)
=over 4
=item * authenticate()
AuthCookie.pm view on Meta::CPAN
be careful. I may change it if I discover that ANY is correct.
=item * authen_cred()
You must define this method yourself in your subclass of
C<Apache::AuthCookie>. Its job is to create the session key that will
be preserved in the user's cookie. The arguments passed to it are:
sub authen_cred ($$\@) {
my $self = shift; # Package name (same as AuthName directive)
my $r = shift; # Apache request object
AuthCookie.pm view on Meta::CPAN
doesn't tamper with the session key. More info in the Eagle book.
=item * authen_ses_key()
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) = @_;
AuthCookie.pm view on Meta::CPAN
Fourth, you might want to take advantage of the new C<logout()>
method, though you certainly don't have to.
=head1 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).
AuthCookie.pm view on Meta::CPAN
get passed to your authen_cred() method.
=item 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 C<$r-E<gt>prev-E<gt>uri>.
See the login.pl script in t/eg/.
=back
In addition, you might want your login page to be able to tell the
difference between a user that sent an incorrect auth cookie, and a
user that sent no auth cookie at all. These typically correspond,
respectively, to users who logged in incorrectly or aren't allowed to
access the given page, and users who are trying to log in for the
first time. To help you differentiate between the two, B<AuthCookie>
will set C<$r-E<gt>subprocess_env('AuthCookieReason')> to either
C<bad_cookie> or C<no_cookie>. 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>.
AuthCookie.pm view on Meta::CPAN
=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/eg/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 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));
AuthCookie.pm view on Meta::CPAN
=back
=head1 CVS REVISION
$Id: AuthCookie.pm,v 2.16 2001/06/01 15:50:27 mschout Exp $
=head1 AUTHOR
Michael Schout <mschout@gkg.net>
view all matches for this distribution
view release on metacpan or search on metacpan
AuthCookieLDAP.pm view on Meta::CPAN
#===============================================================================
#
# Apache::AuthCookieLDAP
#
# An AuthCookie module backed by a LDAP database.
#
# Based on Apache::AuthCookieDBI by Jacob Davies <jacob@sfinteractive.com> <jacob@well.com>
#
# Author: Bjorn Ardo <f98ba@efd.lth.se>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
AuthCookieLDAP.pm view on Meta::CPAN
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
#
#===============================================================================
package Apache::AuthCookieLDAP;
use strict;
use 5.004;
use vars qw( $VERSION );
( $VERSION ) = '$Revision: 0.03 $' =~ /([\d.]+)/;
use Apache::AuthCookie;
use vars qw( @ISA );
@ISA = qw( Apache::AuthCookie );
use Apache;
use Apache::Constants;
use Apache::File;
use Digest::MD5 qw( md5_hex );
AuthCookieLDAP.pm view on Meta::CPAN
# P E R L D O C
#===============================================================================
=head1 NAME
Apache::AuthCookieLDAP - An AuthCookie module backed by a LDAP database.
=head1 VERSION
$Revision: 0.02 $
AuthCookieLDAP.pm view on Meta::CPAN
Not correct!!!
# In httpd.conf or .htaccess
PerlModule Apache::AuthCookieLDAP
PerlSetVar WhatEverPath /
PerlSetVar WhatEverLoginScript /login.pl
# Optional, to share tickets between servers.
PerlSetVar WhatEverDomain .domain.com
AuthCookieLDAP.pm view on Meta::CPAN
PerlSetVar WhatEverLDAP_host ldap.bank.com
PerlSetVar WhatEverLDAP_EncryptionType "none"
PerlSetVar WhatEverLDAP_SessionLifetime 00-24-00-00
# Protected by AuthCookieLDAP.
<Directory /www/domain.com/authcookieldap>
AuthType Apache::AuthCookieLDAP
AuthName WhatEver
PerlAuthenHandler Apache::AuthCookieLDAP->authenticate
PerlAuthzHandler Apache::AuthCookieLDAP->authorize
require valid-user
# or you can require users:
require user jacob
# You can optionally require groups.
require group system
</Directory>
# Login location. *** DEBUG *** I still think this is screwy
<Files LOGIN>
AuthType Apache::AuthCookieLDAP
AuthName WhatEver
SetHandler perl-script
PerlHandler Apache::AuthCookieLDAP->login
</Files>
=head1 DESCRIPTION
This module is an authentication handler that uses the basic mechanism provided
by Apache::AuthCookie with a LDAP database for ticket-based protection. It
is based on two tokens being provided, a username and password, which can
be any strings (there are no illegal characters for either). The username is
used to set the remote user as if Basic Authentication was used.
On an attempt to access a protected location without a valid cookie being
AuthCookieLDAP.pm view on Meta::CPAN
sub _log_not_set($$)
{
my( $r, $variable ) = @_;
my $auth_name = $r->auth_name;
$r->log_error( "Apache::AuthCookieLDAP: $variable not set for auth realm
$auth_name", $r->uri );
}
#-------------------------------------------------------------------------------
# _dir_config_var -- Get a particular authentication variable.
AuthCookieLDAP.pm view on Meta::CPAN
AuthName is PrivateBankingSystem they will look like:
PerlSetVar PrivateBankingSystemLDAP_DN "o=bank.com"
See also L<Apache::Authcookie> for the directives required for any kind
of Apache::AuthCookie-based authentication system.
In the following descriptions, replace "WhatEver" with your particular
AuthName. The available configuration directives are as follows:
=over 4
AuthCookieLDAP.pm view on Meta::CPAN
}
=item C<WhatEverLDAP_SessionLifetime>
How long tickets are good for after being issued. Note that presently
Apache::AuthCookie does not set a client-side expire time, which means that
most clients will only keep the cookie until the user quits the browser.
However, if you wish to force people to log in again sooner than that, set
this value. This can be 'forever' or a life time specified as:
DD-hh-mm-ss -- Days, hours, minute and seconds to live.
AuthCookieLDAP.pm view on Meta::CPAN
my $auth_name = $r->auth_name;
# Username goes in credential_0
my $user = $credentials[ 0 ];
unless ( $user =~ /^.+$/ ) {
$r->log_reason( "Apache::AuthCookieLDAP: no username supplied for auth realm $auth_name", $r->uri );
return 'bad';
}
# Password goes in credential_1
my $password = $credentials[ 1 ];
unless ( $password =~ /^.+$/ ) {
$r->log_reason( "Apache::AuthCookieLDAP: no password supplied for auth realm $auth_name", $r->uri );
return 'bad';
}
# get the configuration information.
my %c = _dbi_config_vars $r;
AuthCookieLDAP.pm view on Meta::CPAN
# Now we calculate the hash of this and the secret key and then
# calculate the hash of *that* and the secret key again.
my $secret_key = $SECRET_KEYS{ $auth_name };
unless ( defined $secret_key ) {
$r->log_reason( "Apache::AuthCookieLDAP: didn't have the secret key for auth realm $auth_name", $r->uri );
return 'bad';
}
my $hash = md5_hex( join ':', $secret_key, md5_hex(
join ':', $public_part, $secret_key
) );
AuthCookieLDAP.pm view on Meta::CPAN
my %c = _dbi_config_vars $r;
# Get the secret key.
my $secret_key = $SECRET_KEYS{ $auth_name };
unless ( defined $secret_key ) {
$r->log_reason( "Apache::AuthCookieLDAP: didn't the secret key from for auth realm $auth_name", $r->uri );
return undef;
}
# Decrypt the session key.
my $session_key;
if ( $c{ LDAP_encryptiontype } eq 'none' ) {
$session_key = $encrypted_session_key;
} else {
# Check that this looks like an encrypted hex-encoded string.
unless ( $encrypted_session_key =~ /^[0-9a-fA-F]+$/ ) {
$r->log_reason( "Apache::AuthCookieLDAP: encrypted session key $encrypted_session_key doesn't look like it's properly hex-encoded for auth realm $auth_name", $r->uri );
return undef;
}
# Get the cipher from the cache, or create a new one if the
# cached cipher hasn't been created, & decrypt the session key.
AuthCookieLDAP.pm view on Meta::CPAN
||= Crypt::CBC->new( $secret_key, 'Blowfish' );
} elsif ( lc $c{ LDAP_encryptiontype } eq 'blowfish_pp' ) {
$cipher = $CIPHERS{ "blowfish_pp:$auth_name" }
||= Crypt::CBC->new( $secret_key, 'Blowfish_PP' );
} else {
$r->log_reason( "Apache::AuthCookieLDAP: unknown encryption type $c{ LDAP_encryptiontype } for auth realm $auth_name", $r->uri );
return undef;
}
$session_key = $cipher->decrypt_hex( $encrypted_session_key );
}
# Break up the session key.
my( $enc_user, $issue_time, $expire_time, $supplied_hash )
= split /:/, $session_key;
# Let's check that we got passed sensible values in the cookie.
unless ( $enc_user =~ /^[a-zA-Z0-9_\%]+$/ ) {
$r->log_reason( "Apache::AuthCookieLDAP: bad percent-encoded user $enc_user recovered from session ticket for auth_realm $auth_name", $r->uri );
return undef;
}
# decode the user
my $user = _percent_decode $enc_user;
unless ( $issue_time =~ /^\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}$/ ) {
$r->log_reason( "Apache::AuthCookieLDAP: bad issue time $issue_time recovered from ticket for user $user for auth_realm $auth_name", $r->uri );
return undef;
}
unless ( $expire_time =~ /^\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}$/ ) {
$r->log_reason( "Apache::AuthCookieLDAP: bad expire time $expire_time recovered from ticket for user $user for auth_realm $auth_name", $r->uri );
return undef;
}
unless ( $supplied_hash =~ /^[0-9a-fA-F]{32}$/ ) {
$r->log_reason( "Apache::AuthCookieLDAP: bad hash $supplied_hash recovered from ticket for user $user for auth_realm $auth_name", $r->uri );
return undef;
}
# Calculate the hash of the user, issue time, expire_time and
# the secret key and then the hash of that and the secret key again.
AuthCookieLDAP.pm view on Meta::CPAN
join ':', $enc_user, $issue_time, $expire_time, $secret_key
) );
# Compare it to the hash they gave us.
unless ( $hash eq $supplied_hash ) {
$r->log_reason( "Apache::AuthCookieLDAP: hash in cookie did not match calculated hash of contents for user $user for auth realm $auth_name", $r->uri );
return undef;
}
# Check that their session hasn't timed out.
if ( _now_year_month_day_hour_minute_second gt $expire_time ) {
$r->log_reason( "Apache:AuthCookieLDAP: expire time $expire_time has passed for user $user for auth realm $auth_name", $r->uri );
return undef;
}
# If we're being paranoid about timing-out long-lived sessions,
# check that the issue time + the current (server-set) session lifetime
AuthCookieLDAP.pm view on Meta::CPAN
# They must be okay, so return the user.
return $user;
}
###########################################################################
# This is taken from AuthCookieDBI and checks user groups from a database #
###########################################################################
sub group($$$)
AuthCookieLDAP.pm view on Meta::CPAN
# See if we have a row in the groups table for this user/group.
my $dbh = DBI->connect( $c{ DBI_DSN },
$c{ DBI_user }, $c{ DBI_password } );
unless ( defined $dbh ) {
$r->log_reason( "Apache::AuthCookieDBI: couldn't connect to $c{ DBI_DSN } for auth realm $auth_name", $r->uri );
return undef;
}
# Now loop through all the groups to see if we're a member of any:
my $sth = $dbh->prepare( <<"EOS" );
AuthCookieLDAP.pm view on Meta::CPAN
EOS
foreach my $group ( @groups ) {
$sth->execute( $group, $user );
return OK if ( $sth->fetchrow_array );
}
$r->log_reason( "Apache::AuthCookieDBI: user $user was not a member of any of the required groups @groups for auth realm $auth_name", $r->uri );
return FORBIDDEN;
}
AuthCookieLDAP.pm view on Meta::CPAN
<f98ba@efd.lth.se>
=head1 SEE ALSO
Apache::AuthCookie(1)
=cut
view all matches for this distribution
view release on metacpan or search on metacpan
lib/Apache/AuthCookieNTLM.pm view on Meta::CPAN
package Apache::AuthCookieNTLM;
# Small wrapper to Apache::AuthenNTLM to store user login details to cookie
# and reduce the number of PDC requests.
use strict;
use Data::Dumper;
use Apache::Constants ':common';
use Apache::Request;
use Apache::Cookie;
use Apache::AuthenNTLM;
use base ('Apache::AuthenNTLM');
use vars qw($VERSION);
$VERSION = 0.07;
lib/Apache/AuthCookieNTLM.pm view on Meta::CPAN
my $debug = $r->dir_config('ntlmdebug') || 0;
# Set cookie name
my $cname = $config{name} || $auth_type . '_' . $auth_name;
print STDERR "AuthCookieNTLM - Looking for Cookie Name: $cname\n" if $debug > 0;
# Look for cookie
my $t = Apache::Request->new($self);
my %cookiejar = Apache::Cookie->new($t)->parse;
if (!defined $cookiejar{$cname}
or ($r->method eq 'POST' and $r->header_in('content-length') == 0)){
# Don't have the cookie, try authenticate
my $v = Apache::AuthenNTLM::handler ($self, $r);
if ($v == 0 && $cookie_values ne {}) {
# Set the cookie as we have user details
my $cookie = Apache::Cookie->new($r,
-name => $cname,
-value => $cookie_values,
-path => $config{'path'} || "/",
);
$cookie->expires($config{'expires'}) if defined $config{'expires'};
$cookie->domain($config{'domain'}) if defined $config{'domain'};
$cookie->secure('1') if defined $config{'secure'};
# Set the cookie to header
$r->header_out('Set-Cookie' => $cookie->bake());
if($debug > 0) {
print STDERR "AuthCookieNTLM - Setting Cookie Expire: " . $config{'expires'} . "\n" if $debug > 0 && defined $config{'expires'};
print STDERR "AuthCookieNTLM - Setting Cookie Domain: " . $config{'domain'} . "\n" if $debug > 0 && defined $config{'domain'};
print STDERR "AuthCookieNTLM - Setting Cookie Secure: " . $config{'secure'} . "\n" if $debug > 1 && defined $config{'secure'};
print STDERR "AuthCookieNTLM - Setting Cookie values: " . Dumper($cookie_values) . "\n" if $debug > 1;
}
}
# AuthenNTLM loops so have to behave like it does
# and return $v
return $v;
} else {
print STDERR "AuthCookieNTLM - Found Cookies for '$cname'\n" if $debug > 0;
my %c = $cookiejar{$cname}->parse();
if(defined $c{$cname}) {
print STDERR "AuthCookieNTLM - Cookie Matched \n" if $debug > 1;
my %v = $c{$cname}->value();
print STDERR "AuthCookieNTLM - Cookie values " . Dumper(\%v) . "\n" if $debug > 1;
if(defined $v{'username'} && defined $v{'userdomain'}) {
my $user = lc($v{'userdomain'} . '\\' . $v{'username'});
$r ->user($user) if ref($r) eq 'Apache';
print STDERR "AuthCookieNTLM - REMOVE_USER SET: " . $user . "\n" if $debug > 1;
}
}
}
return OK;
lib/Apache/AuthCookieNTLM.pm view on Meta::CPAN
__END__
=head1 NAME
Apache::AuthCookieNTLM - NTLM (Windows domain) authentication with cookies
=head1 SYNOPSIS
'WhatEver' should be replaced with the AuthName you choose
for this location's authentication.
<Location />
PerlAuthenHandler Apache::AuthCookieNTLM
# NTLM CONFIG
AuthType ntlm,basic
AuthName WhatEver
require valid-user
lib/Apache/AuthCookieNTLM.pm view on Meta::CPAN
As explained in the Apache::AuthenNTLM module, depending on the user's
config, IE will supply your Windows logon credentials to the web server
when the server asks for NTLM authentication. This saves the user typing in
their windows login and password.
Apache::AuthCookieNTLM is an interface to Shannon Peevey's
Apache::AuthenNTLM module. This modules authenticates a user
using their Windows login against the Windows PDC, but to also
stores their login name into a cookie. This means that it can be
accessed from other pages and stops the system having to
authenticate for every request.
We did consider using Apache::AuthCookie to store the details in a
cookie but since using NTLM is basicaly there to remove the need
to login and is almost exclusively for intranets (as it needs access
to the PDC), we decided it was feasible not to use it.
=head1 APACHE CONFIGURATION
lib/Apache/AuthCookieNTLM.pm view on Meta::CPAN
for this location's authentication.
=head2 PerlSetVar WhatEverName
Sets the cookie name. This will default to
Apache::AuthCookieNTLM_WhatEver.
=head2 PerlSetVar WhatEverExpires
Sets the cookie expiry time. This defaults to being
a session only cookie.
lib/Apache/AuthCookieNTLM.pm view on Meta::CPAN
This is an example of how to set your cookie values with whatever
data you want.
package MYAuthenNTLM;
use Apache::AuthCookieNTLM;
use base ( 'Apache::AuthCookieNTLM' );
use MyUserLookup_Package;
sub choose_cookie_values {
my ($self,$r) = @_;
lib/Apache/AuthCookieNTLM.pm view on Meta::CPAN
PerlAuthenHandler Apache::AuthenNTLM
with
PerlAuthenHandler Apache::AuthCookieNTLM
And have it all just work[tm].
Remember to quit IE and reload as it's crap at implementing
changes on the fly!
lib/Apache/AuthCookieNTLM.pm view on Meta::CPAN
your error log, but you can just ignore it.
=head1 SEE ALSO
L<Apache::AuthenNTLM>,
L<Apache::Cookie>,
L<CGI::Cookie>
=head1 AUTHOR
Leo Lapworth <llap@cuckoo.org>, Francoise Dehinbo
view all matches for this distribution
view release on metacpan or search on metacpan
AuthCookiePAM.pm view on Meta::CPAN
#===============================================================================
#
# Apache::AuthCookiePAM
#
# An AuthCookie module backed by a PAM.
#
# Copyright (C) 2002 SF Interactive.
#
# Author: Vandana Awasthi
#
AuthCookiePAM.pm view on Meta::CPAN
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
#===============================================================================
package Apache::AuthCookiePAM;
use strict;
use 5.004;
use vars qw( $VERSION );
( $VERSION ) = '$Revision: 1.0 $' =~ /([\d.]+)/;
use Apache;
use Apache::Table;
use Apache::Constants qw(:common M_GET FORBIDDEN REDIRECT);
use Apache::AuthCookie::Util;
use Apache::Util qw(escape_uri);
use Apache::AuthCookie;
use Authen::PAM;
use vars qw( @ISA );
@ISA = qw( Apache::AuthCookie );
use Apache::File;
use Digest::MD5 qw( md5_hex );
use Date::Calc qw( Today_and_Now Add_Delta_DHMS );
# Also uses Crypt::CBC if you're using encrypted cookies.
AuthCookiePAM.pm view on Meta::CPAN
# P E R L D O C
#===============================================================================
=head1 NAME
Apache::AuthCookiePAM - An AuthCookie module backed by a PAM .
=head1 VERSION
$Revision: 1.0 $
AuthCookiePAM.pm view on Meta::CPAN
# This PerlSetVar MUST precede the PerlModule line because the
# key is read in a BEGIN block when the module is loaded.
PerlSetVar WhatEverPaM_SecretKeyFile /etc/httpd/acme.com.key
PerlSetVar WhatEverPAM_service login
PerlModule Apache::AuthCookiePAM
PerlSetVar WhatEverPath /
PerlSetVar WhatEverLoginScript /login.pl
# Optional, to share tickets between servers.
PerlSetVar WhatEverDomain .domain.com
PerlSetVar WhatEverChangePwdScript /changepwd.pl
# These are optional, the module sets sensible defaults.
PerlSetVar WhatEverPAM_SessionLifetime 00-24-00-00
# Protected by AuthCookiePAM.
<Directory /www/domain.com/authcookiepam>
AuthType Apache::AuthCookiePAM
AuthName WhatEver
PerlAuthenHandler Apache::AuthCookiePAM->authenticate
PerlAuthzHandler Apache::AuthCookiePAM->authorize
require valid-user
</Directory>
# Login location. *** DEBUG *** I still think this is screwy
<Files LOGIN>
AuthType Apache::AuthCookiePAM
AuthName WhatEver
SetHandler perl-script
PerlHandler Apache::AuthCookiePAM->login
</Files>
<Files ChangePwd>
AuthType Apache::AuthCookiePAM
AuthName WhatEver
SetHandler perl-script
PerlHandler Apache::AuthCookiePAM->changepwd
</Files>
=head1 DESCRIPTION
This module is an authentication handler that uses the basic mechanism
provided by Apache::AuthCookie with PAM (based on DBI) . It is based on
two tokens being provided, a username and password, which can be any
strings (there are no illegal characters for either). The username is
used to set the remote user as if Basic Authentication was used.
On an attempt to access a protected location without a valid cookie being
AuthCookiePAM.pm view on Meta::CPAN
sub _log_not_set($$)
{
my( $r, $variable ) = @_;
my $auth_name; $auth_name = $r->auth_name;
$r->log_error( "Apache::AuthCookiePAM: $variable not set for auth realm
$auth_name", $r->uri );
}
#-------------------------------------------------------------------------------
# _dir_config_var -- Get a particular authentication variable.
AuthCookiePAM.pm view on Meta::CPAN
PerlSetVar ProvateBankingSystemLoginScript /bvsm/login.pl
See also L<Apache::Authcookie> for the directives required for any kind
of Apache::AuthCookie-based authentication system.
In the following descriptions, replace "WhatEver" with your particular
AuthName. The available configuration directives are as follows:
=over 4
AuthCookiePAM.pm view on Meta::CPAN
}
=item C<WhatEverPAM_SessionLifetime>
How long tickets are good for after being issued. Note that presently
Apache::AuthCookie does not set a client-side expire time, which means that
most clients will only keep the cookie until the user quits the browser.
However, if you wish to force people to log in again sooner than that, set
this value. This can be 'forever' or a life time specified as:
DD-hh-mm-ss -- Days, hours, minute and seconds to live.
AuthCookiePAM.pm view on Meta::CPAN
# Username goes in credential_0
my $user; $user = $credentials[ 0 ];
$user=~ tr/A-Z/a-z/;
unless ( $user =~ /^.+$/ ) {
$r->log_reason( "Apache::AuthCookiePAM: no username supplied for auth realm $auth_name", $r->uri );
$r->subprocess_env('AuthenReason', 'No username provided. Try again.');
return undef;
}
# Password goes in credential_1
my $password; $password = $credentials[ 1 ];
unless ( $password =~ /^.+$/ ) {
$r->log_reason( "Apache::AuthCookiePAM: no password supplied for auth realm $auth_name", $r->uri );
$r->subprocess_env('AuthenReason', 'No password provided. Try again.');
return undef;
}
# service to be used for authentication
my $service; $service = $c{PAM_service};
AuthCookiePAM.pm view on Meta::CPAN
# Now we calculate the hash of this and the secret key and then
# calculate the hash of *that* and the secret key again.
my $secret_key; $secret_key = $SECRET_KEYS{ $auth_name };
unless ( defined $secret_key ) {
$r->log_reason( "Apache::AuthCookiePAM: didn't have the secret key for auth realm $auth_name", $r->uri );
return 'bad';
}
my $hash ; $hash = md5_hex( join ':', $secret_key, md5_hex(
join ':', $public_part, $secret_key
) );
AuthCookiePAM.pm view on Meta::CPAN
my %c; %c = _config_vars $r;
# Get the secret key.
my $secret_key; $secret_key = $SECRET_KEYS{ $auth_name };
unless ( defined $secret_key ) {
$r->log_reason( "Apache::AuthCookiePAM: didn't the secret key from for auth realm $auth_name", $r->uri );
return undef;
}
# Decrypt the session key.
my $session_key;
if ( $c{ PAM_encryptiontype } eq 'none' ) {
$session_key = $encrypted_session_key;
} else {
# Check that this looks like an encrypted hex-encoded string.
unless ( $encrypted_session_key =~ /^[0-9a-fA-F]+$/ ) {
$r->log_reason( "Apache::AuthCookiePAM: encrypted session key $encrypted_session_key doesn't look like it's properly hex-encoded for auth realm $auth_name", $r->uri );
return undef;
}
# Get the cipher from the cache, or create a new one if the
# cached cipher hasn't been created, & decrypt the session key.
AuthCookiePAM.pm view on Meta::CPAN
||= Crypt::CBC->new( $secret_key, 'Blowfish' );
} elsif ( lc $c{ PAM_encryptiontype } eq 'blowfish_pp' ) {
$cipher = $CIPHERS{ "blowfish_pp:$auth_name" }
||= Crypt::CBC->new( $secret_key, 'Blowfish_PP' );
} else {
$r->log_reason( "Apache::AuthCookiePAM: unknown encryption type $c{ PAM_encryptiontype } for auth realm $auth_name", $r->uri );
return undef;
}
$session_key = $cipher->decrypt_hex( $encrypted_session_key );
}
# Break up the session key.
my( $enc_user, $issue_time, $expire_time, $supplied_hash )
= split /:/, $session_key;
# Let's check that we got passed sensible values in the cookie.
unless ( $enc_user =~ /^[a-zA-Z0-9_\%]+$/ ) {
$r->log_reason( "Apache::AuthCookiePAM: bad percent-encoded user $enc_user recovered from session ticket for auth_realm $auth_name", $r->uri );
return undef;
}
# decode the user
my $user; $user = _percent_decode $enc_user;
unless ( $issue_time =~ /^\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}$/ ) {
$r->log_reason( "Apache::AuthCookiePAM: bad issue time $issue_time recovered from ticket for user $user for auth_realm $auth_name", $r->uri );
return undef;
}
unless ( $expire_time =~ /^\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}$/ ) {
$r->log_reason( "Apache::AuthCookiePAM: bad expire time $expire_time recovered from ticket for user $user for auth_realm $auth_name", $r->uri );
return undef;
}
unless ( $supplied_hash =~ /^[0-9a-fA-F]{32}$/ ) {
$r->log_reason( "Apache::AuthCookiePAM: bad hash $supplied_hash recovered from ticket for user $user for auth_realm $auth_name", $r->uri );
return undef;
}
# Calculate the hash of the user, issue time, expire_time and
# the secret key and then the hash of that and the secret key again.
AuthCookiePAM.pm view on Meta::CPAN
join ':', $enc_user, $issue_time, $expire_time, $secret_key
) );
# Compare it to the hash they gave us.
unless ( $hash eq $supplied_hash ) {
$r->log_reason( "Apache::AuthCookiePAM: hash in cookie did not match calculated hash of contents for user $user for auth realm $auth_name", $r->uri );
return undef;
}
# Check that their session hasn't timed out.
if ( _now_year_month_day_hour_minute_second gt $expire_time ) {
$r->log_reason( "Apache:AuthCookiePAM: expire time $expire_time has passed for user $user for auth realm $auth_name", $r->uri );
return undef;
}
# If we're being paranoid about timing-out long-lived sessions,
# check that the issue time + the current (server-set) session lifetime
AuthCookiePAM.pm view on Meta::CPAN
my ($self, $r, $args) ;
($self, $r, $args) = @_;
return unless $r->method eq 'POST';
my $debug ; $debug = $r->dir_config("AuthCookieDebug") || 0;
$r->log_error("Converting POST -> GET") if $debug >= 2;
my @pairs ; @pairs =();
my ($name, $value);
AuthCookiePAM.pm view on Meta::CPAN
sub changepwd ($$)
{
my ($self, $r) ;
($self, $r) = @_;
my $debug; $debug = $r->dir_config("AuthCookieDebug") || 0;
my ($auth_type, $auth_name);
($auth_type, $auth_name) = ($r->auth_type, $r->auth_name);
my %args; %args = $r->method eq 'POST' ? $r->content : $r->args;
AuthCookiePAM.pm view on Meta::CPAN
my @credentials;
#user in credential_0
my $user; $user = $args{"credential_0"};
$user=~ tr/A-Z/a-z/;
unless ( $user =~ /^.+$/ ) {
$r->log_reason( "Apache::AuthCookiePAM: no username supplied for auth realm $auth_name", $r->uri );
}
# Old Password goes in credential_1
my $oldpassword; $oldpassword = $args{"credential_1"};
unless ( $oldpassword =~ /^.+$/ ) {
$r->log_reason( "Apache::AuthCookiePAM: no password supplied ", $r->uri );
}
# New Password goes in credential_2
my $newpassword ; $newpassword = $args{"credential_2"};
unless ( $newpassword =~ /^.+$/ ) {
$r->log_reason( "Apache::AuthCookiePAM: no password supplied ", $r->uri );
}
# Repeat Password goes in credential_3
my $confirmpassword; $confirmpassword = $args{"credential_3"};
unless ( $confirmpassword =~ /^.+$/ ) {
$r->log_reason( "Apache::AuthCookiePAM: passwords don't match", $r->uri );
}
# Now do password change
#
my ($pamh,$res);
AuthCookiePAM.pm view on Meta::CPAN
$pamh=0;
undef $pamh;
if ( $res == PAM_SUCCESS()) {
$r->subprocess_env('AuthenReason', 'Password Updated. Please login with your new password');
$r->log_reason("AuthenCookiePAM:". $args{'destination'}."Password for $user Updated. Please login with your new password");
#
$auth_type->logout($r);
$r->err_header_out("Location" => $args{'destination'});
return REDIRECT;
}
else {
$r->subprocess_env('AuthenReason', "Password Not Updated. New password did not satisfy specified rules or failed authentication");
$r->log_reason("AuthenCookiePAM: Password for $user Not Updated. ");
return $auth_type->changepwd_form($user);
}
}
#-------------------------------------------------------------------------------
AuthCookiePAM.pm view on Meta::CPAN
Vandana Awasthi
=head1 SEE ALSO
Apache::AuthCookie(1)
=cut
view all matches for this distribution
view release on metacpan or search on metacpan
AuthCookieURL.pm view on Meta::CPAN
package Apache::AuthCookieURL;
use strict;
use mod_perl qw(1.24 StackedHandlers MethodHandlers Authen Authz);
use Apache::Constants qw(:common M_GET REDIRECT MOVED);
use vars qw($VERSION);
use Apache::URI ();
use Apache::Cookie;
use constant DEBUG => 'AuthCookieURLDebug';
# $Id: AuthCookieURL.pm,v 1.3 2000/11/21 00:46:01 lii Exp $
$VERSION = sprintf '%d.%03d', q$Revision: 1.3 $ =~ /: (\d+)\.(\d+)/;
#======================== NOTE ============================================
### This module is a modification of Ken Williams <ken@forum.swarthmore.edu>
### Apache::AuthCookie apache module.
# Modified July 14, 2000 to handle munged urls and sessions w/o login
# - use cookies or munged urls for sessions
# - can be used with a login script, or without for simple session management
# - Will create sessions without overriding, if you don't care how unique they are.
AuthCookieURL.pm view on Meta::CPAN
sub recognize_user ($$) {
my ($self, $r) = @_;
my $debug = $r->dir_config( DEBUG ) || 0;
my ($auth_type, $auth_name) = ($r->auth_type, $r->auth_name);
return unless $auth_type && $auth_name;
# return unless $r->header_in('Cookie');
my ($cookie) = ($r->header_in( 'Cookie' ) || '') =~ /${auth_type}_$auth_name=([^;]+)/;
# Get session from URI if not set in a cookie
# (won't likely be here if this isn't a protected doc)
$cookie ||= $r->notes( 'URI_Session' ) || '';
AuthCookieURL.pm view on Meta::CPAN
} else {
# Delete error message cookie, if found
$self->send_cookie( value=>'none', name=>'Reason', expires=>'-1d' )
if ($r->header_in( 'Cookie' ) || '') =~ /${auth_type}_${auth_name}Reason/;
$r->log_error("ses_key returned from authen_cred = '$ses_key'" ) if $debug >= 2;
AuthCookieURL.pm view on Meta::CPAN
my ($self,$r) = @_;
my $debug = $r->dir_config( DEBUG ) || 0;
my ($auth_type, $auth_name) = ($r->auth_type, $r->auth_name);
# Send the Set-Cookie header to expire the auth cookie.
$self->send_cookie(value=>'none', expires=>'-1d');
return FORBIDDEN;
# This doesn't seem to work.
AuthCookieURL.pm view on Meta::CPAN
$r->log_error( '** In authenticate **' ) if $debug >= 3;
$r->log_error( "auth_type= '$auth_type'" ) if $debug >= 3;
# This is a way to open up some documents/directories
return OK if lc $r->auth_name eq 'none';
return OK if $r->dir_config('DisableAuthCookieURL');
# Only authenticate the first internal request
return OK unless $r->is_initial_req;
AuthCookieURL.pm view on Meta::CPAN
## Check and get session from cookie or URL ##
# Get the Cookie header. If there is a session key for this realm, strip
# off everything but the value of the cookie.
my ($ses_key_cookie) = ($r->header_in( 'Cookie' ) || "") =~ /${auth_type}_$auth_name=([^;]+)/;
my $cookie = $ses_key_cookie || '';
# Get session from URI if not set in a cookie
AuthCookieURL.pm view on Meta::CPAN
$r->log_error("requested uri = '" . $r->uri . "'" ) if $debug >= 2;
unless ($ses_key_cookie) {
$r->subprocess_env( AuthCookieURLReason => 'no_session_provided' );
} else {
# Check and convert the session key into a user
AuthCookieURL.pm view on Meta::CPAN
$r->connection->auth_type($auth_type);
$r->connection->user($auth_user);
$r->log_error("user authenticated as $auth_user. Exiting Authen") if $debug >= 1;
$r->log_error( "Cookie: '$cookie' and URI_Session: '" . ($r->notes( 'URI_Session' ) || '') ."'") if $debug >= 4;
# Clean up the path by redirecting if cookies are in use
if ( $cookie && $r->notes( 'URI_Session' ) ) {
my $query = $r->args ? '?' . $r->args : '';
$query = $r->uri . $query;
$r->log_error("Cookies are in use -- redirecting to '$query'") if $debug >= 3;
# prevent the error_document from adding the session back in.
$r->notes('SESSION', undef );
$r->header_out( Location => $query );
AuthCookieURL.pm view on Meta::CPAN
# Do this even if no cookie was sent -- can't hurt.
$auth_type->send_cookie( value=>'vanish', expires=>'-1d');
$r->subprocess_env( AuthCookieURLReason => 'bad_session_provided' );
}
}
# Invalid or no session was provided -- send to the login form
AuthCookieURL.pm view on Meta::CPAN
$r->log_error( "** In authorize **" ) if $debug >= 3;
# This is a way to open up some documents/directories
return OK if lc $r->auth_name eq 'none';
return OK if $r->dir_config('DisableAuthCookieURL');
return OK unless $r->is_initial_req; #only the first internal request
# How to solve the problem of protecting from the root downward?
AuthCookieURL.pm view on Meta::CPAN
my ($self, %settings ) = @_;
my $r = Apache->request();
my ( $auth_name, $auth_type ) = ( $r->auth_name, $r->auth_type );
return if $r->dir_config( $auth_name . 'NoCookie' );
$settings{name} = $settings{name}
? "${auth_type}_$auth_name$settings{name}"
: "${auth_type}_$auth_name";
AuthCookieURL.pm view on Meta::CPAN
my @deletes = grep { ! defined $settings{$_} } keys %settings;
delete $settings{$_} for @deletes;
$settings{path} ||= '/'; # need to do this so will return cookie when url is munged.
my $cookie = Apache::Cookie->new( $r, %settings );
$cookie->bake;
my $debug = $r->dir_config( DEBUG ) || 0;
$r->log_error('Send cookie: ' . $cookie->as_string ) if $debug >= 3;
AuthCookieURL.pm view on Meta::CPAN
sub key {
my $self = shift;
my $r = Apache->request;
my ( $auth_name, $auth_type ) = ( $r->auth_name, $r->auth_type );
my ( $ses_key_cookie ) = ($r->header_in( 'Cookie' ) || '') =~ /${auth_type}_$auth_name=([^;]+)/;
return $ses_key_cookie || $r->notes( 'URI_Session' ) || undef;
}
1;
__END__
=head1 NAME
Apache::AuthCookieURL - Perl Authentication and Authorization
or session management via cookies or URL munging
=head1 SYNOPSIS
In httpd.conf
# Your module that overrides AuthCookieURL methods
PerlModule My::AuthCookieURLHandler
# Or to use simple session generation w/o persistence
#PerlModule Apache::AuthCookieURL
## Some settings -- "Whatever" is set by AuthName ##
# most can be set within <directory> sections
# Send expires with cookie
AuthCookieURL.pm view on Meta::CPAN
# Or for just session management without a login script
#PerlSetVar WhateverLoginScript NONE
# Debugging options
#PerlSetVar AuthCookieURLDebug 5
# Disable cookies (only URL based sessions)
#PerlSetVar WhateverNoCookie 1
# Define a string that indicates to AuthCookieURL
# what a session looks like
# This can only be in main config
#PerlSetVar SessionPrefix Session-
# This block enables URL session handling
PerlTransHandler Apache::AuthCookieURLHandler->URLsession
ErrorDocument 302 /MISSING
ErrorDocument 301 /MISSING
<Location /MISSING>
SetHandler perl-script
PerlHandler Apache::AuthCookieURLHandler->error_document
</Location>
<Location /protected>
AuthType Apache::AuthCookieURLHandler
AuthName Whatever
PerlAuthenHandler Apache::AuthCookieURLHandler->authenticate
PerlAuthzHandler Apache::AuthCookieURLHandler->authorize
require valid-user
</Location>
# provide open access to some areas below
<Location /protected/open>
PerlSetVar DisableAuthCookieURL 1
</Location>
# or if the entire directory tree was protected
<Location /images>
PerlSetVar DisableAuthCookieURL 1
</Location>
# Make sure the login script can be run
<Files login.pl>
AuthCookieURL.pm view on Meta::CPAN
</Files>
# LOGIN is the action defined by the login.pl script
<Files LOGIN>
AuthType Apache::AuthCookieURLHandler
AuthName Whatever
SetHandler perl-script
PerlHandler Apache::AuthCookieURLHandler->login
</Files>
# Note: If protecting the entire web site (from root down) then
# the action *must* be C</LOGIN> as the module looks for this string.
# better to just invalidate the session, of course
<Files LOGOUT>
AuthType Apache::AuthCookieURLHandler
PerlSetVar WhateverLogoutURI /
AuthName Whatever
SetHandler perl-script
PerlHandler Apache::AuthCookieURLHandler->logout
</Files>
=head1 DESCRIPTION
** Warning: beta software. This should be used for testing purposes only.
That said, there are a few people using it and I've been using it for a
few months without problem. The interface may change (or disappear) without notice.
Please report any problems or comments back to Bill Moseley E<lt>moseley@hank.orgE<gt>.
This module is a modification of Ken Williams E<lt>ken@forum.swarthmore.eduE<gt> Apache::AuthCookie.
Please see perldoc Apache::AuthCookie for complete instructions. As this is intended to be
a drop-in replacement for Apache::AuthCookie you may wish to install and test with Ken's
Apache::AuthCookie before trying AuthCookieURL.
Basically, this module allows you to catch any unauthenticated access and redirect to a
login script that you define. The login script posts credentials (e.g. username and password)
and your module can then validate and provide a session key. The session key is sent in a cookie,
and also in a munged URL and a redirect is issued and the process starts all over.
Typically, you will write your own module that will override methods in Apache::AuthCookieURL.
These methods are described completely in Ken's Apache::AuthCookie. Your methods will be used
to generate and validate session keys. You can use Apache::AuthCookieURL without overriding
its methods and then AuthCookieURL can be used as a simple session manager.
With this module you should be able to enable session management for an entire site
using E<lt>Location /E<gt>, and then allow access to, say, the images directory, and also require
password access to other locations. One issue at this point is that the session key is
stripped from URLs in a Trans handler. So you would need to use cookies to use different
session keys for different parts of your web tree.
Apache::AuthCookieURL adds the following features to Apache::AuthCookie.
=over 4
=item * URL munging
AuthCookieURL.pm view on Meta::CPAN
information via the environment.
=item * Simple Session Management
If the login script is set to `NONE' with PerlSetVar WhateverLoginScript NONE then
Apache::AuthCookeURL acts like a simple session manager: your module will provide a new
session key if one is not provided with the request, or if the one provided is invalid.
=item * Really Simple Session Management
Apache::AuthCookieURL provides default authen_cred() and authen_ses_key() methods that
generates a (questionably) random session key. This means you can use AuthCookieURL
directly without subclassing for really simple session management without any persistence of
session keys.
=back
Unless you are not subclassing this module (and using the default methods provide),
your own module must define two methods: authen_cred() and authen_ses_key(), and then
subclass by including Apache::AuthCookieURL in your module's @ISA array.
Again, please see Apache::AuthCookie for
complete documentation.
=over 4
=item * authen_cred()
AuthCookieURL.pm view on Meta::CPAN
messages based on that returned session (error) code.
=item * authen_ses_key()
This method's job is to validate and convert a session key into a username and return it.
AuthCookieURL places the returned value into $ENV{REMOTE_USER}.
=back
=head1 CONFIGURATION SETTINGS
AuthCookieURL.pm view on Meta::CPAN
if you want a setting to override a global setting, then use it within a E<lt>directoryE<gt>,
E<lt>fileE<gt>, or E<lt>locationE<gt> section.
=over 4
=item * AuthCookieURLDebug
Sets the debugging level. Since some debugging info is generated in the Trans
handler this needs to be set in the main httpd config. Default is 0.
Example: PerlSetVar AuthCookieURLDebug 5
=item * SessionPrefix
SessionPrefix sets the prefix used by the Trans handler to recognize the session
in the URL (thus needs to be set in the main config), and to create the session ID.
AuthCookieURL.pm view on Meta::CPAN
Sets where you are redirected after requesting the logout URL (see SYNOPSIS).
Defaults to '/'.
Example: PerlSetVar WhateverLogoutURI /gone.html
=item * DisableAuthCookieURL
This causes the Authen and Authz handlers to return OK. In other words,
<Location /protected/notprotected>
PerlSetVar DisableAuthCookieURL 1
</Location>
Allows full access to the notprotected directory.
AuthCookieURL.pm view on Meta::CPAN
This sets the Login script to be executed when authorization is
required (no valid session key was sent by cookie or URL). This login script can be a
CGI script, Apache::Registry script, or a mod_perl handler.
If set to `NONE' then AuthCookieURL will be in simple session management mode.
AuthCookieURL-E<gt>login will be called which calls authen_cred() to generate a session key.
authen_cred() should just return a session key without checking the credentials.
If you do not override AuthCookieURL::authen_cred(), then AuthCookieURL::authen_cred()
simply returns this for a session key.
return time . $$ . int rand $$;
Example: PerlSetVar WhateverLoginScript /login.pl
PerlSetVar WhateverLoginScript NONE
=item * WhateverNoCookie
Turns off cookies.
Example: PerlSetVar WhateverNoCookie 1
=item * Whatever(Path|Expires|Domain|Secure)
These all control the values sent in cookies. Path, if used, must be '/' if
using URL-based sessions.
AuthCookieURL.pm view on Meta::CPAN
=back
=head1 ENVIRONMENT AND NOTES
Apache::AuthCookieURL sets some environment variables and Apache notes:
authen_ses_key() returns a value that is placed in $ENV{REMOTE_USER}. authen_ses_key()
normally converts the session key into a username.
$ENV{SESSION} contains the current session key
$ENV{AuthCookieURLReason} contains the reason authentication failed. Either
'no_session_provided' or 'bad_session_provided'.
$r-E<gt>notes( 'URI_Session' ) is the session extracted from the URI
$r-E<gt>notes('Session_prefix') is the prefix used with the session keys, of course.
AuthCookieURL.pm view on Meta::CPAN
browsers, leak outside your site, and are broken if your pages use absolute links to other
pages on-site.
=head1 TO DO
Apache::AuthCookieURL uses error documents to try to fixup any redirects. The obvious
example is when a request is made for a directory without a trailing slash and Apache
issues a redirect. (Actually, AuthCookieURL tries to detect this case and rewrite the URL
before Apache redirects.) I wish I knew a better way to fixup Location: headers in
redirects without sub-requesting every request. There's no way to catch a CGI script
or module that might issue a Location: header or REDIRECT.
I guess that's left for Apache 2.0 when all output can be filtered.
=head1 REQUIRED
mod_perl 1.24, Apache::Cookie
=head1 AUTHOR
Bill Moseley E<lt>moseley@hank.orgE<gt> made minor changes to Ken Williams' E<lt>ken@forum.swarthmore.eduE<gt>
Apache::AuthCookie.
Thanks very much to Ken for Apache::AuthCookie.
=head1 VERSION
$Revision: 1.3 $
=head1 SEE ALSO
L<Apache::AuthCookie>
=cut
view all matches for this distribution
view release on metacpan or search on metacpan
$r->note_basic_auth_failure $r->note_digest_auth_failure()
[none] $r->compare_digest_response()
see Recipe 13.8 in the mod_perl Developer's Cookbook for a far more
detailed explanantion than will be covered here.
=over 4
=item new()
=head1 EXAMPLE
for a complete example, see the My/DigestAuthenticator.pm file
in the test suite for this package, as well as AuthDigest.pm.
In general, the steps are the same as for Basic authentication,
examples of which abound on CPAN, the Eagle book, and the Cookbook:
use Apache::AuthDigest::API;
sub handler {
This module is free software. It may be used, redistributed
and/or modified under the same terms as Perl itself.
=head1 HISTORY
This code is derived from the I<Cookbook::DigestAPI> module,
available as part of "The mod_perl Developer's Cookbook".
For more information, visit http://www.modperlcookbook.org/
=cut
view all matches for this distribution