6 Catalyst::Authentication::Store::LDAP::Backend
7 - LDAP authentication storage backend.
11 # you probably just want Store::LDAP under most cases,
12 # but if you insist you can instantiate your own store:
14 use Catalyst::Authentication::Store::LDAP::Backend;
18 Authentication::Credential::Password
22 'ldap_server' => 'ldap1.yourcompany.com',
23 'ldap_server_options' => {
26 'binddn' => 'anonymous',
27 'bindpw' => 'dontcarehow',
29 'start_tls_options' => {
32 'user_basedn' => 'ou=people,dc=yourcompany,dc=com',
33 'user_filter' => '(&(objectClass=posixAccount)(uid=%s))',
34 'user_scope' => 'one', # or 'sub' for Active Directory
35 'user_field' => 'uid',
36 'user_search_options' => {
38 'attrs' => [qw( distinguishedname name mail )],
40 'user_results_filter' => sub { return shift->pop_entry },
41 'entry_class' => 'MyApp::LDAP::Entry',
42 'user_class' => 'MyUser',
44 'role_basedn' => 'ou=groups,dc=yourcompany,dc=com',
45 'role_filter' => '(&(objectClass=posixGroup)(member=%s))',
46 'role_scope' => 'one',
49 'role_search_options' => {
52 'role_search_as_user' => 0,
53 'persist_in_session' => 'all',
56 our $users = Catalyst::Authentication::Store::LDAP::Backend->new(\%config);
60 You probably want L<Catalyst::Authentication::Store::LDAP>.
62 Otherwise, this lets you create a store manually.
64 See the L<Catalyst::Authentication::Store::LDAP> documentation for
65 an explanation of the configuration options.
71 package Catalyst::Authentication::Store::LDAP::Backend;
72 use base qw( Class::Accessor::Fast );
77 our $VERSION = '1.016';
79 use Catalyst::Authentication::Store::LDAP::User;
81 use Catalyst::Utils ();
82 use Catalyst::Exception;
85 __PACKAGE__->mk_accessors(
86 qw( ldap_server ldap_server_options binddn
87 bindpw entry_class user_search_options
88 user_filter user_basedn user_scope
89 user_attrs user_field use_roles role_basedn
90 role_filter role_scope role_field role_value
91 role_search_options start_tls start_tls_options
92 user_results_filter user_class role_search_as_user
100 Creates a new L<Catalyst::Authentication::Store::LDAP::Backend> object.
101 $config should be a hashref, which should contain the configuration options
102 listed in L<Catalyst::Authentication::Store::LDAP>'s documentation.
104 Also sets a few sensible defaults.
109 my ( $class, $config ) = @_;
111 unless ( defined($config) && ref($config) eq "HASH" ) {
112 Catalyst::Exception->throw(
113 "Catalyst::Authentication::Store::LDAP::Backend needs to be configured with a hashref."
116 my %config_hash = %{$config};
117 $config_hash{'binddn'} ||= 'anonymous';
118 $config_hash{'user_filter'} ||= '(uid=%s)';
119 $config_hash{'user_scope'} ||= 'sub';
120 $config_hash{'user_field'} ||= 'uid';
121 $config_hash{'role_filter'} ||= '(memberUid=%s)';
122 $config_hash{'role_scope'} ||= 'sub';
123 $config_hash{'role_field'} ||= 'cn';
124 $config_hash{'use_roles'} = '1'
125 unless exists $config_hash{use_roles};
126 $config_hash{'start_tls'} ||= '0';
127 $config_hash{'entry_class'} ||= 'Catalyst::Model::LDAP::Entry';
128 $config_hash{'user_class'}
129 ||= 'Catalyst::Authentication::Store::LDAP::User';
130 $config_hash{'role_search_as_user'} ||= 0;
131 $config_hash{'persist_in_session'} ||= 'username';
132 Catalyst::Exception->throw('persist_in_session must be either username or all')
133 unless $config_hash{'persist_in_session'} =~ /\A(?:username|all)\z/;
135 Catalyst::Utils::ensure_class_loaded( $config_hash{'user_class'} );
136 my $self = \%config_hash;
137 bless( $self, $class );
141 =head2 find_user( I<authinfo>, $c )
143 Creates a L<Catalyst::Authentication::Store::LDAP::User> object
144 for the given User ID. This is the preferred mechanism for getting a
145 given User out of the Store.
147 I<authinfo> should be a hashref with a key of either C<id> or
148 C<username>. The value will be compared against the LDAP C<user_field> field.
153 my ( $self, $authinfo, $c ) = @_;
154 return $self->get_user( $authinfo->{id} || $authinfo->{username}, $c );
157 =head2 get_user( I<id>, $c)
159 Creates a L<Catalyst::Authentication::Store::LDAP::User> object
160 for the given User ID, or calls C<new> on the class specified in
161 C<user_class>. This instance of the store object, the results of
162 C<lookup_user> and $c are passed as arguments (in that order) to C<new>.
163 This is the preferred mechanism for getting a given User out of the Store.
168 my ( $self, $id, $c ) = @_;
169 my $user = $self->user_class->new( $self, $self->lookup_user($id), $c );
175 Returns a L<Net::LDAP> object, connected to your LDAP server. (According
176 to how you configured the Backend, of course)
183 if ( defined( $self->ldap_server_options() ) ) {
185 = Net::LDAP->new( $self->ldap_server,
186 %{ $self->ldap_server_options } )
187 or Catalyst::Exception->throw($@);
190 $ldap = Net::LDAP->new( $self->ldap_server )
191 or Catalyst::Exception->throw($@);
193 if ( defined( $self->start_tls ) && $self->start_tls =~ /(1|true)/i ) {
195 if ( defined( $self->start_tls_options ) ) {
196 $mesg = $ldap->start_tls( %{ $self->start_tls_options } );
199 $mesg = $ldap->start_tls;
201 if ( $mesg->is_error ) {
202 Catalyst::Exception->throw( "TLS Error: " . $mesg->error );
208 =head2 ldap_bind($ldap, $binddn, $bindpw)
210 Bind's to the directory. If $ldap is undef, it will connect to the
211 LDAP server first. $binddn should be the DN of the object you wish
212 to bind as, and $bindpw the password.
214 If $binddn is "anonymous", an anonymous bind will be performed.
219 my ( $self, $ldap, $binddn, $bindpw ) = @_;
220 $ldap ||= $self->ldap_connect;
221 if ( !defined($ldap) ) {
222 Catalyst::Exception->throw("LDAP Server undefined!");
225 # if username is present, make sure password is present too.
226 # see https://rt.cpan.org/Ticket/Display.html?id=81908
227 if ( !defined $binddn ) {
228 $binddn = $self->binddn;
229 $bindpw = $self->bindpw;
232 if ( $binddn eq "anonymous" ) {
233 $self->_ldap_bind_anon($ldap);
237 my $mesg = $ldap->bind( $binddn, 'password' => $bindpw );
238 if ( $mesg->is_error ) {
239 Catalyst::Exception->throw(
240 "Error on Initial Bind: " . $mesg->error );
244 $self->_ldap_bind_anon( $ldap, $binddn );
250 sub _ldap_bind_anon {
251 my ( $self, $ldap, $dn ) = @_;
252 my $mesg = $ldap->bind($dn);
253 if ( $mesg->is_error ) {
254 Catalyst::Exception->throw( "Error on Bind: " . $mesg->error );
258 =head2 ldap_auth( $binddn, $bindpw )
260 Connect to the LDAP server and do an authenticated bind against the
261 directory. Throws an exception if connecting to the LDAP server fails.
262 Returns 1 if binding succeeds, 0 if it fails.
267 my ( $self, $binddn, $bindpw ) = @_;
268 my $ldap = $self->ldap_connect;
269 if ( !defined $ldap ) {
270 Catalyst::Exception->throw("LDAP server undefined!");
272 my $mesg = $ldap->bind( $binddn, password => $bindpw );
273 return $mesg->is_error ? 0 : 1;
276 =head2 lookup_user($id)
278 Given a User ID, this method will:
280 A) Bind to the directory using the configured binddn and bindpw
281 B) Perform a search for the User Object in the directory, using
282 user_basedn, user_filter, and user_scope.
283 C) Assuming we found the object, we will walk its attributes
284 using L<Net::LDAP::Entry>'s get_value method. We store the
285 results in a hashref. If we do not find the object, then
287 D) Return a hashref that looks like:
290 'ldap_entry' => $entry, # The Net::LDAP::Entry object
291 'attributes' => $attributes,
294 This method is usually only called by find_user().
299 my ( $self, $id ) = @_;
301 # Trim trailing space or we confuse ourselves
303 my $ldap = $self->ldap_bind;
305 if ( defined( $self->user_basedn ) ) {
306 push( @searchopts, 'base' => $self->user_basedn );
309 Catalyst::Exception->throw(
310 "You must set user_basedn before looking up users!");
312 my $filter = $self->_replace_filter( $self->user_filter, $id );
313 push( @searchopts, 'filter' => $filter );
314 push( @searchopts, 'scope' => $self->user_scope );
315 if ( defined( $self->user_search_options ) ) {
316 push( @searchopts, %{ $self->user_search_options } );
318 my $usersearch = $ldap->search(@searchopts);
320 return undef if ( $usersearch->is_error );
323 my $user_field = $self->user_field;
324 my $results_filter = $self->user_results_filter;
326 if ( defined($results_filter) ) {
327 $entry = &$results_filter($usersearch);
330 $entry = $usersearch->pop_entry;
332 if ( $usersearch->pop_entry ) {
333 Catalyst::Exception->throw(
334 "More than one entry matches user search.\n"
335 . "Consider defining a user_results_filter sub." );
338 # a little extra sanity check with the 'eq' since LDAP already
340 # NOTE that Net::LDAP returns exactly what you asked for, but
341 # because LDAP is often case insensitive, FoO can match foo
342 # and so we normalize with lc().
343 if ( defined($entry) ) {
344 unless ( lc( $entry->get_value($user_field) ) eq lc($id) ) {
345 Catalyst::Exception->throw(
346 "LDAP claims '$user_field' equals '$id' but results entry does not match."
354 unless ($userentry) {
358 foreach my $attr ( $userentry->attributes ) {
359 my @attrvalues = $userentry->get_value($attr);
360 if ( scalar(@attrvalues) == 1 ) {
361 $attrhash->{ lc($attr) } = $attrvalues[0];
364 $attrhash->{ lc($attr) } = \@attrvalues;
368 eval { Catalyst::Utils::ensure_class_loaded( $self->entry_class ) };
370 bless( $userentry, $self->entry_class );
371 $userentry->{_use_unicode}++;
374 'ldap_entry' => $userentry,
375 'attributes' => $attrhash,
380 =head2 lookup_roles($userobj, [$ldap])
382 This method looks up the roles for a given user. It takes a
383 L<Catalyst::Authentication::Store::LDAP::User> object
384 as its first argument, and can optionally take a I<Net::LDAP> object which
385 is used rather than the default binding if supplied.
387 It returns an array containing the role_field attribute from all the
388 objects that match its criteria.
393 my ( $self, $userobj, $ldap ) = @_;
394 if ( $self->use_roles == 0 || $self->use_roles =~ /^false$/i ) {
397 $ldap ||= $self->role_search_as_user
398 ? $userobj->ldap_connection : $self->ldap_bind;
400 if ( defined( $self->role_basedn ) ) {
401 push( @searchopts, 'base' => $self->role_basedn );
404 Catalyst::Exception->throw(
405 "You must set up role_basedn before looking up roles!");
407 my $filter_value = $userobj->has_attribute( $self->role_value );
408 if ( !defined($filter_value) ) {
409 Catalyst::Exception->throw( "User object "
413 . " attribute, so I can't look up its roles!" );
415 my $filter = $self->_replace_filter( $self->role_filter, $filter_value );
416 push( @searchopts, 'filter' => $filter );
417 push( @searchopts, 'scope' => $self->role_scope );
418 push( @searchopts, 'attrs' => [ $self->role_field ] );
419 if ( defined( $self->role_search_options ) ) {
420 push( @searchopts, %{ $self->role_search_options } );
422 my $rolesearch = $ldap->search(@searchopts);
424 RESULT: foreach my $entry ( $rolesearch->entries ) {
425 push( @roles, $entry->get_value( $self->role_field ) );
430 sub _replace_filter {
434 $replace =~ s/([*()\\\x{0}])/sprintf '\\%02x', ord($1)/ge;
435 $filter =~ s/\%s/$replace/g;
442 Catalyst::Authentication::Store::LDAP::User->supports(@_).
449 # this can work as a class method
450 Catalyst::Authentication::Store::LDAP::User->supports(@_);
453 =head2 from_session( I<id>, I<$c>, $frozenuser )
455 Revives a serialized user from storage in the session.
457 Supports users stored with a different persist_in_session setting.
462 my ( $self, $c, $frozenuser ) = @_;
464 # we need to restore the user depending on the current storage of the
465 # user in the session store which might differ from what
466 # persist_in_session is set to now
467 if ( ref $frozenuser eq 'HASH' ) {
468 # we can rely on the existance of this key if the user is a hashref
469 if ( $frozenuser->{persist_in_session} eq 'all' ) {
470 return $self->user_class->new( $self, $frozenuser->{user}, $c, $frozenuser->{_roles} );
474 return $self->get_user( $frozenuser, $c );
483 Adam Jacob <holoway@cpan.org>
485 Some parts stolen shamelessly and entirely from
486 L<Catalyst::Plugin::Authentication::Store::Htpasswd>.
488 Currently maintained by Peter Karman <karman@cpan.org>.
492 To nothingmuch, ghenry, castaway and the rest of #catalyst for the help. :)
496 L<Catalyst::Authentication::Store::LDAP>, L<Catalyst::Authentication::Store::LDAP::User>, L<Catalyst::Plugin::Authentication>, L<Net::LDAP>
498 =head1 COPYRIGHT & LICENSE
500 Copyright (c) 2005 the aforementioned authors. All rights
501 reserved. This program is free software; you can redistribute
502 it and/or modify it under the same terms as Perl itself.