3 package Catalyst::Plugin::Authentication;
5 use base qw/Class::Accessor::Fast Class::Data::Inheritable/;
8 __PACKAGE__->mk_accessors(qw/_user/);
9 __PACKAGE__->mk_classdata($_) for qw/_auth_realms/;
18 # this optimization breaks under Template::Toolkit
19 # use user_exists instead
22 # constant->import(have_want => eval { require Want });
25 our $VERSION = "0.10";
27 sub set_authenticated {
28 my ( $c, $user, $realmname ) = @_;
31 $c->request->{user} = $user; # compatibility kludge
34 $realmname = 'default';
37 if ( $c->isa("Catalyst::Plugin::Session")
38 and $c->config->{authentication}{use_session}
39 and $user->supports("session") )
41 $c->save_user_in_session($realmname, $user);
43 $user->_set_auth_realm($realmname);
45 $c->NEXT::set_authenticated($user, $realmname);
48 sub _should_save_user_in_session {
49 my ( $c, $user ) = @_;
51 $c->_auth_sessions_supported
52 and $c->config->{authentication}{use_session}
53 and $user->supports("session");
56 sub _should_load_user_from_session {
57 my ( $c, $user ) = @_;
59 $c->_auth_sessions_supported
60 and $c->config->{authentication}{use_session}
61 and $c->session_is_valid;
64 sub _auth_sessions_supported {
66 $c->isa("Catalyst::Plugin::Session");
76 if ( defined(my $user = $c->_user) ) {
79 return $c->auth_restore_user;
83 # change this to allow specification of a realm - to verify the user is part of that realm
84 # in addition to verifying that they exist.
87 return defined($c->_user) || defined($c->_user_in_session);
91 sub save_user_in_session {
92 my ( $c, $realmname, $user ) = @_;
94 $c->session->{__user_realm} = $realmname;
96 # we want to ask the backend for a user prepared for the session.
97 # but older modules split this functionality between the user and the
98 # backend. We try the store first. If not, we use the old method.
99 my $realm = $c->get_auth_realm($realmname);
100 if ($realm->{'store'}->can('for_session')) {
101 $c->session->{__user} = $realm->{'store'}->for_session($c, $user);
103 $c->session->{__user} = $user->for_session;
113 $c->isa("Catalyst::Plugin::Session")
114 and $c->config->{authentication}{use_session}
115 and $c->session_is_valid
117 delete @{ $c->session }{qw/__user __user_realm/};
120 $c->NEXT::logout(@_);
124 my ( $c, $userinfo, $realmname ) = @_;
126 $realmname ||= 'default';
127 my $realm = $c->get_auth_realm($realmname);
128 if ( $realm->{'store'} ) {
129 return $realm->{'store'}->find_user($userinfo, $c);
131 $c->log->debug('find_user: unable to locate a store matching the requested realm');
136 sub _user_in_session {
139 return unless $c->_should_load_user_from_session;
141 return $c->session->{__user};
144 sub _store_in_session {
147 # we don't need verification, it's only called if _user_in_session returned something useful
149 return $c->session->{__user_store};
152 sub auth_restore_user {
153 my ( $c, $frozen_user, $realmname ) = @_;
155 $frozen_user ||= $c->_user_in_session;
156 return unless defined($frozen_user);
158 $realmname ||= $c->session->{__user_realm};
159 return unless $realmname; # FIXME die unless? This is an internal inconsistency
161 my $realm = $c->get_auth_realm($realmname);
162 $c->_user( my $user = $realm->{'store'}->from_session( $c, $frozen_user ) );
164 # this sets the realm the user originated in.
165 $user->_set_auth_realm($realmname);
170 # we can't actually do our setup in setup because the model has not yet been loaded.
171 # So we have to trigger off of setup_finished. :-(
175 $c->_authentication_initialize();
179 ## the actual initialization routine. whee.
180 sub _authentication_initialize {
183 if ($c->_auth_realms) { return };
185 my $cfg = $c->config->{'authentication'} || {};
193 $c->_auth_realms($realmhash);
195 ## BACKWARDS COMPATIBILITY - if realm is not defined - then we are probably dealing
196 ## with an old-school config. The only caveat here is that we must add a classname
197 if (exists($cfg->{'realms'})) {
199 foreach my $realm (keys %{$cfg->{'realms'}}) {
200 $c->setup_auth_realm($realm, $cfg->{'realms'}{$realm});
203 # if we have a 'default-realm' in the config hash and we don't already
204 # have a realm called 'default', we point default at the realm specified
205 if (exists($cfg->{'default_realm'}) && !$c->get_auth_realm('default')) {
206 $c->set_default_auth_realm($cfg->{'default_realm'});
209 foreach my $storename (keys %{$cfg->{'stores'}}) {
211 store => $cfg->{'stores'}{$storename},
213 $c->setup_auth_realm($storename, $realmcfg);
221 sub setup_auth_realm {
222 my ($app, $realmname, $config) = @_;
224 $app->log->debug("Setting up $realmname");
225 if (!exists($config->{'store'}{'class'})) {
226 Carp::croak "Couldn't setup the authentication realm named '$realmname', no class defined";
230 my $storeclass = $config->{'store'}{'class'};
232 ## follow catalyst class naming - a + prefix means a fully qualified class, otherwise it's
233 ## taken to mean C::P::A::Store::(specifiedclass)::Backend
234 if ($storeclass !~ /^\+(.*)$/ ) {
235 $storeclass = "Catalyst::Plugin::Authentication::Store::${storeclass}::Backend";
241 # a little niceness - since most systems seem to use the password credential class,
242 # if no credential class is specified we use password.
243 $config->{credential}{class} ||= "Catalyst::Plugin::Authentication::Credential::Password";
245 my $credentialclass = $config->{'credential'}{'class'};
247 ## follow catalyst class naming - a + prefix means a fully qualified class, otherwise it's
248 ## taken to mean C::P::A::Credential::(specifiedclass)
249 if ($credentialclass !~ /^\+(.*)$/ ) {
250 $credentialclass = "Catalyst::Plugin::Authentication::Credential::${credentialclass}";
252 $credentialclass = $1;
255 # if we made it here - we have what we need to load the classes;
256 Catalyst::Utils::ensure_class_loaded( $credentialclass );
257 Catalyst::Utils::ensure_class_loaded( $storeclass );
259 # BACKWARDS COMPATIBILITY - if the store class does not define find_user, we define it in terms
260 # of get_user and add it to the class. this is because the auth routines use find_user,
261 # and rely on it being present. (this avoids per-call checks)
262 if (!$storeclass->can('find_user')) {
264 *{"${storeclass}::find_user"} = sub {
265 my ($self, $info) = @_;
266 my @rest = @{$info->{rest}} if exists($info->{rest});
267 $self->get_user($info->{id}, @rest);
271 $app->auth_realms->{$realmname}{'store'} = $storeclass->new($config->{'store'}, $app);
272 if ($credentialclass->can('new')) {
273 $app->auth_realms->{$realmname}{'credential'} = $credentialclass->new($config->{'credential'}, $app);
275 # if the credential class is not actually a class - has no 'new' operator, we wrap it,
276 # once again - to allow our code to be simple at runtime and allow non-OO packages to function.
277 my $wrapperclass = 'Catalyst::Plugin::Authentication::Credential::Wrapper';
278 Catalyst::Utils::ensure_class_loaded( $wrapperclass );
279 $app->auth_realms->{$realmname}{'credential'} = $wrapperclass->new($config->{'credential'}, $app);
285 return($self->_auth_realms);
289 my ($app, $realmname) = @_;
290 return $app->auth_realms->{$realmname};
293 sub set_default_auth_realm {
294 my ($app, $realmname) = @_;
296 if (exists($app->auth_realms->{$realmname})) {
297 $app->auth_realms->{'default'} = $app->auth_realms->{$realmname};
299 return $app->get_auth_realm('default');
303 my ($app, $userinfo, $realmname) = @_;
306 $realmname = 'default';
309 my $realm = $app->get_auth_realm($realmname);
311 if ($realm && exists($realm->{'credential'})) {
312 my $user = $realm->{'credential'}->authenticate($app, $realm->{store}, $userinfo);
314 $app->set_authenticated($user, $realmname);
318 $app->log->debug("The realm requested, '$realmname' does not exist," .
319 " or there is no credential associated with it.")
324 ## BACKWARDS COMPATIBILITY -- Warning: Here be monsters!
326 # What follows are backwards compatibility routines - for use with Stores and Credentials
327 # that have not been updated to work with C::P::Authentication v0.10.
328 # These are here so as to not break people's existing installations, but will go away
329 # in a future version.
331 # The old style of configuration only supports a single store, as each store module
332 # sets itself as the default store upon being loaded. This is the only supported
333 # 'compatibility' mode.
337 my ( $c, $uid, @rest ) = @_;
339 return $c->find_user( {'id' => $uid, 'rest'=>\@rest }, 'default' );
343 ## this should only be called when using old-style authentication plugins. IF this gets
344 ## called in a new-style config - it will OVERWRITE the store of your default realm. Don't do it.
345 ## also - this is a partial setup - because no credential is instantiated... in other words it ONLY
346 ## works with old-style auth plugins and C::P::Authentication in compatibility mode. Trying to combine
347 ## this with a realm-type config will probably crash your app.
348 sub default_auth_store {
351 if ( my $new = shift ) {
352 $self->auth_realms->{'default'}{'store'} = $new;
353 my $storeclass = ref($new);
355 # BACKWARDS COMPATIBILITY - if the store class does not define find_user, we define it in terms
356 # of get_user and add it to the class. this is because the auth routines use find_user,
357 # and rely on it being present. (this avoids per-call checks)
358 if (!$storeclass->can('find_user')) {
360 *{"${storeclass}::find_user"} = sub {
361 my ($self, $info) = @_;
362 my @rest = @{$info->{rest}} if exists($info->{rest});
363 $self->get_user($info->{id}, @rest);
368 return $self->get_auth_realm('default')->{'store'};
371 ## BACKWARDS COMPATIBILITY
372 ## this only ever returns a hash containing 'default' - as that is the only
373 ## supported mode of calling this.
374 sub auth_store_names {
377 my %hash = ( $self->get_auth_realm('default')->{'store'} => 'default' );
381 my ( $self, $name ) = @_;
383 if ($name ne 'default') {
384 Carp::croak "get_auth_store called on non-default realm '$name'. Only default supported in compatibility mode";
386 $self->default_auth_store();
390 sub get_auth_store_name {
391 my ( $self, $store ) = @_;
395 # sub auth_stores is only used internally - here for completeness
399 my %hash = ( 'default' => $self->get_auth_realm('default')->{'store'});
415 Catalyst::Plugin::Authentication - Infrastructure plugin for the Catalyst
416 authentication framework.
425 $c->authenticate({ username => 'myusername', password => 'mypassword' });
426 my $age = $c->user->get('age');
431 The authentication plugin provides generic user support. It is the basis
432 for both authentication (checking the user is who they claim to be), and
433 authorization (allowing the user to do what the system authorises them to do).
435 Using authentication is split into two parts. A Store is used to actually
436 store the user information, and can store any amount of data related to
437 the user. Multiple stores can be accessed from within one application.
438 Credentials are used to verify users, using the store, given data from
441 To implement authentication in a Catalyst application you need to add this
442 module, plus at least one store and one credential module.
444 Authentication data can also be stored in a session, if the application
445 is using the L<Catalyst::Plugin::Session> module.
449 =head2 The Authentication/Authorization Process
451 Web applications typically need to identify a user - to tell the user apart
452 from other users. This is usually done in order to display private information
453 that is only that user's business, or to limit access to the application so
454 that only certain entities can access certain parts.
456 This process is split up into several steps. First you ask the user to identify
457 themselves. At this point you can't be sure that the user is really who they
460 Then the user tells you who they are, and backs this claim with some piece of
461 information that only the real user could give you. For example, a password is
462 a secret that is known to both the user and you. When the user tells you this
463 password you can assume they're in on the secret and can be trusted (ignore
464 identity theft for now). Checking the password, or any other proof is called
465 B<credential verification>.
467 By this time you know exactly who the user is - the user's identity is
468 B<authenticated>. This is where this module's job stops, and other plugins step
469 in. The next logical step is B<authorization>, the process of deciding what a
470 user is (or isn't) allowed to do. For example, say your users are split into
471 two main groups - regular users and administrators. You should verify that the
472 currently logged in user is indeed an administrator before performing the
473 actions of an administrative part of your application. One way to do this is
474 with role based access control.
476 =head2 The Components In This Framework
478 =head3 Credential Verifiers
480 When user input is transferred to the L<Catalyst> application (typically via
481 form inputs) this data then enters the authentication framework through these
484 These plugins check the data, and ensure that it really proves the user is who
487 =head3 Storage Backends
489 The credentials also identify a user, and this family of modules is supposed to
490 take this identification data and return a standardized object oriented
491 representation of users.
493 When a user is retrieved from a store it is not necessarily authenticated.
494 Credential verifiers can either accept a user object, or fetch the object
495 themselves from the default store.
497 =head3 The Core Plugin
499 This plugin on its own is the glue, providing store registration, session
500 integration, and other goodness for the other plugins.
504 More layers of plugins can be stacked on top of the authentication code. For
505 example, L<Catalyst::Plugin::Session::PerUser> provides an abstraction of
506 browser sessions that is more persistent per users.
507 L<Catalyst::Plugin::Authorization::Roles> provides an accepted way to separate
508 and group users into categories, and then check which categories the current
513 Let's say we were storing users in an Apache style htpasswd file. Users are
514 stored in that file, with a hashed password and some extra comments. Users are
515 verified by supplying a password which is matched with the file.
517 This means that our application will begin like this:
523 Authentication::Credential::Password
524 Authentication::Store::Htpasswd
527 __PACKAGE__->config->{authentication}{htpasswd} = "passwdfile";
529 This loads the appropriate methods and also sets the htpasswd store as the
532 So, now that we have the code loaded we need to get data from the user into the
535 Let's create an authentication controller:
537 package MyApp::Controller::Auth;
540 my ( $self, $c ) = @_;
542 if ( my $user = $c->req->param("user")
543 and my $password = $c->req->param("password") )
545 if ( $c->login( $user, $password ) ) {
546 $c->res->body( "hello " . $c->user->name );
556 This code should be very readable. If all the necessary fields are supplied,
557 call the L<Authentication::Credential::Password/login> method on the
558 controller. If that succeeds the user is logged in.
560 It could be simplified though:
563 my ( $self, $c ) = @_;
570 Since the C<login> method knows how to find logically named parameters on its
573 The credential verifier will ask the default store to get the user whose ID is
574 the user parameter. In this case the default store is the htpasswd one. Once it
575 fetches the user from the store the password is checked and if it's OK
576 C<< $c->user >> will contain the user object returned from the htpasswd store.
578 We can also pass a user object to the credential verifier manually, if we have
579 several stores per app. This is discussed in
580 L<Catalyst::Plugin::Authentication::Store>.
582 Now imagine each admin user has a comment set in the htpasswd file saying
585 A restricted action might look like this:
587 sub restricted : Local {
588 my ( $self, $c ) = @_;
590 $c->detach("unauthorized")
591 unless $c->user_exists
592 and $c->user->extra_info() eq "admin";
594 # do something restricted here
597 This is somewhat similar to role based access control.
598 L<Catalyst::Plugin::Authentication::Store::Htpasswd> treats the extra info
599 field as a comma separated list of roles if it's treated that way. Let's
600 leverage this. Add the role authorization plugin:
607 sub restricted : Local {
608 my ( $self, $c ) = @_;
610 $c->detach("unauthorized") unless $c->check_roles("admin");
612 # do something restricted here
615 This is somewhat simpler and will work if you change your store, too, since the
616 role interface is consistent.
618 Let's say your app grew, and you now have 10000 users. It's no longer efficient
619 to maintain an htpasswd file, so you move this data to a database.
623 Authentication::Credential::Password
624 Authentication::Store::DBIC
628 __PACKAGE__->config->{authentication}{dbic} = ...; # see the DBIC store docs
630 The rest of your code should be unchanged. Now let's say you are integrating
631 typekey authentication to your system. For simplicity's sake we'll assume that
632 the user's are still keyed in the same way.
636 Authentication::Credential::Password
637 Authentication::Credential::TypeKey
638 Authentication::Store::DBIC
642 And in your auth controller add a new action:
644 sub typekey : Local {
645 my ( $self, $c ) = @_;
647 if ( $c->authenticate_typekey) { # uses $c->req and Authen::TypeKey
648 # same stuff as the $c->login method
653 You've now added a new credential verification mechanizm orthogonally to the
654 other components. All you have to do is make sure that the credential verifiers
655 pass on the same types of parameters to the store in order to retrieve user
664 Returns the currently logged in user or undef if there is none.
668 Whether or not a user is logged in right now.
670 The reason this method exists is that C<< $c->user >> may needlessly load the
671 user from the auth store.
673 If you're just going to say
675 if ( $c->user_exists ) {
678 $c->forward("login");
681 it should be more efficient than C<< $c->user >> when a user is marked in the
682 session but C<< $c->user >> hasn't been called yet.
686 Delete the currently logged in user from C<user> and the session.
690 Fetch a particular users details, defined by the given ID, via the default store.
700 Whether or not to store the user's logged in state in the session, if the
701 application is also using the L<Catalyst::Plugin::Session> plugin. This
702 value is set to true per default.
706 If multiple stores are being used, set the module you want as default here.
710 If multiple stores are being used, you need to provide a name for each store
711 here, as a hash, the keys are the names you wish to use, and the values are
712 the the names of the plugins.
715 __PACKAGE__->config( authentication => {
716 store => 'Catalyst::Plugin::Authentication::Store::HtPasswd',
718 'dbic' => 'Catalyst::Plugin::Authentication::Store::DBIC'
724 =head1 METHODS FOR STORE MANAGEMENT
728 =item default_auth_store
730 Return the store whose name is 'default'.
732 This is set to C<< $c->config->{authentication}{store} >> if that value exists,
733 or by using a Store plugin:
735 use Catalyst qw/Authentication Authentication::Store::Minimal/;
737 Sets the default store to
738 L<Catalyst::Plugin::Authentication::Store::Minimal::Backend>.
741 =item get_auth_store $name
743 Return the store whose name is $name.
745 =item get_auth_store_name $store
747 Return the name of the store $store.
751 A hash keyed by name, with the stores registered in the app.
753 =item auth_store_names
755 A ref-hash keyed by store, which contains the names of the stores.
757 =item register_auth_stores %stores_by_name
759 Register stores into the application.
763 =head1 INTERNAL METHODS
767 =item set_authenticated $user
769 Marks a user as authenticated. Should be called from a
770 C<Catalyst::Plugin::Authentication::Credential> plugin after successful
773 This involves setting C<user> and the internal data in C<session> if
774 L<Catalyst::Plugin::Session> is loaded.
776 =item auth_restore_user $user
778 Used to restore a user from the session, by C<user> only when it's actually
781 =item save_user_in_session $user
783 Used to save the user in a session.
787 Revives a user from the session object if there is one.
791 Sets the default configuration parameters.
799 This list might not be up to date.
801 =head2 User Storage Backends
803 L<Catalyst::Plugin::Authentication::Store::Minimal>,
804 L<Catalyst::Plugin::Authentication::Store::Htpasswd>,
805 L<Catalyst::Plugin::Authentication::Store::DBIC> (also works with Class::DBI).
807 =head2 Credential verification
809 L<Catalyst::Plugin::Authentication::Credential::Password>,
810 L<Catalyst::Plugin::Authentication::Credential::HTTP>,
811 L<Catalyst::Plugin::Authentication::Credential::TypeKey>
815 L<Catalyst::Plugin::Authorization::ACL>,
816 L<Catalyst::Plugin::Authorization::Roles>
818 =head2 Internals Documentation
820 L<Catalyst::Plugin::Authentication::Store>
824 L<Catalyst::Plugin::Session>,
825 L<Catalyst::Plugin::Session::PerUser>
827 =head1 DON'T SEE ALSO
829 This module along with its sub plugins deprecate a great number of other
830 modules. These include L<Catalyst::Plugin::Authentication::Simple>,
831 L<Catalyst::Plugin::Authentication::CDBI>.
833 At the time of writing these plugins have not yet been replaced or updated, but
834 should be eventually: L<Catalyst::Plugin::Authentication::OpenID>,
835 L<Catalyst::Plugin::Authentication::LDAP>,
836 L<Catalyst::Plugin::Authentication::CDBI::Basic>,
837 L<Catalyst::Plugin::Authentication::Basic::Remote>.
841 Yuval Kogman, C<nothingmuch@woobling.org>
847 =head1 COPYRIGHT & LICENSE
849 Copyright (c) 2005 the aforementioned authors. All rights
850 reserved. This program is free software; you can redistribute
851 it and/or modify it under the same terms as Perl itself.