Journal(2005) | Blog(2006) | RandomLink | WhoAmI | LiveBookmark | HomePage

<<Previous: 用 prototype 来写 Ctrl+Enter 提交表单  >>Next: Share the URLs (November 2005)

modperl 的用户验证

Category: mod_perl   Keywords: PerlAuthenHandler apache modperl

这种形式创建的用户名和密码必须要用 htpasswd
而一般我们都把用户名和密码存在数据库里,这样比较方便增加和修改用户密码等。
在 modperl 中这一块是使用 PerlAuthenHandler 来处理的。

一个事例代码如下:

package MyApache2::MyAuth;

use strict;
use warnings;

use Apache2::Access ();
use Apache2::RequestRec ();
use Apache2::Const -compile => qw(OK DECLINED HTTP_UNAUTHORIZED);

use DBI;
my $dbh = DBI->connect("DBI:mysql:auth:localhost",
       'root', undef, { RaiseError => 1, PrintError => 1 }) or die "cann't connect";

sub handler {
   my $r = shift;

   my ($status, $password) = $r->get_basic_auth_pw;
   return $status unless $status == Apache2::Const::OK;

   my $sth = $dbh->prepare("SELECT password FROM users WHERE username = ?");
   $sth->execute($r->user);
   my @turepwd = $sth->fetchrow_array();

   if ($password eq $turepwd[0]) {
       return Apache2::Const::OK;
   }

   $r->note_basic_auth_failure;
   return Apache2::Const::HTTP_UNAUTHORIZED;
}

1;

然后在 perl.conf 里面添加
Alias /auth/ "E:/Fayland/auth/"
<Location /auth/>
SetHandler perl-script
PerlResponseHandler ModPerl::Registry
PerlAuthenHandler MyApache2::MyAuth
Options +ExecCGI

AuthType Basic
AuthName "Fayland's Test WebSite"
Require valid-user
</Location>
上面就是一个简单的例子。这里没有使用 Apache::DBI 而是直接使用了 DBI 是为了简便。

这中间你还可以更复杂点,针对不同的 $status 返回不同的东西。用户名不存在返回什么,密码错误返回什么的。
不过大致的代码就是这个样子了。更详细的查看 Apache/modperl 文档:
http://perl.apache.org/docs/2.0/user/handlers/http.html#PerlAuthenHandler

<<Previous: 用 prototype 来写 Ctrl+Enter 提交表单  >>Next: Share the URLs (November 2005)

Options: +Del.icio.us

Related items Created on 2005-11-26 00:08:37, Last modified on 2005-11-26 00:14:00
Copyright 2004-2005 All Rights Reserved. Powered by Eplanet && Catalyst 5.62.