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_stores _auth_store_names/;
18 # this optimization breaks under Template::Toolkit
19 # use user_exists instead
22 # constant->import(have_want => eval { require Want });
25 our $VERSION = "0.09";
27 sub set_authenticated {
28 my ( $c, $user ) = @_;
31 $c->request->{user} = $user; # compatibility kludge
33 if ( $c->_should_save_user_in_session($user) ) {
34 $c->save_user_in_session($user);
37 $c->NEXT::set_authenticated($user);
40 sub _should_save_user_in_session {
41 my ( $c, $user ) = @_;
43 $c->_auth_sessions_supported
44 and $c->config->{authentication}{use_session}
45 and $user->supports("session");
48 sub _should_load_user_from_session {
49 my ( $c, $user ) = @_;
51 $c->_auth_sessions_supported
52 and $c->config->{authentication}{use_session}
53 and $c->session_is_valid;
56 sub _auth_sessions_supported {
58 $c->isa("Catalyst::Plugin::Session");
68 if ( defined(my $user = $c->_user) ) {
71 return $c->auth_restore_user;
77 return defined($c->_user) || defined($c->_user_in_session);
80 sub save_user_in_session {
81 my ( $c, $user ) = @_;
83 my $store = $user->store || ref $user;
84 $c->session->{__user_store} = $c->get_auth_store_name($store) || $store;
85 $c->session->{__user} = $user->for_session;
93 if ( $c->_should_load_user_from_session ) {
94 $c->_delete_user_from_session();
100 sub _delete_user_from_session {
102 delete @{ $c->session }{qw/__user __user_store/};
106 my ( $c, $uid, @rest ) = @_;
108 if ( my $store = $c->default_auth_store ) {
109 return $store->get_user( $uid, @rest );
112 Catalyst::Exception->throw(
113 "The user id $uid was passed to an authentication "
114 . "plugin, but no default store was specified" );
118 sub _user_in_session {
121 return unless $c->_should_load_user_from_session;
123 return $c->session->{__user};
126 sub _store_in_session {
129 # we don't need verification, it's only called if _user_in_session returned something useful
131 return $c->session->{__user_store};
134 sub auth_restore_user {
135 my ( $c, $frozen_user, $store_name ) = @_;
137 $frozen_user ||= $c->_user_in_session;
138 return unless defined($frozen_user);
140 $store_name ||= $c->_store_in_session;
141 return unless $store_name; # FIXME die unless? This is an internal inconsistency
143 my $store = $c->get_auth_store($store_name);
145 $c->_user( my $user = $store->from_session( $c, $frozen_user ) );
154 my $cfg = $c->config->{authentication} ||= {};
161 $c->register_auth_stores(
162 default => $cfg->{store},
163 %{ $cfg->{stores} || {} },
170 my ( $self, $name ) = @_;
171 $self->auth_stores->{$name} || ( Class::Inspector->loaded($name) && $name );
174 sub get_auth_store_name {
175 my ( $self, $store ) = @_;
176 $self->auth_store_names->{$store};
179 sub register_auth_stores {
180 my ( $self, %new ) = @_;
182 foreach my $name ( keys %new ) {
183 my $store = $new{$name} or next;
184 $self->auth_stores->{$name} = $store;
185 $self->auth_store_names->{$store} = $name;
191 $self->_auth_stores(@_) || $self->_auth_stores( {} );
194 sub auth_store_names {
197 $self->_auth_store_names || do {
198 tie my %hash, 'Tie::RefHash';
199 $self->_auth_store_names( \%hash );
203 sub default_auth_store {
206 if ( my $new = shift ) {
207 $self->register_auth_stores( default => $new );
210 $self->get_auth_store("default");
221 Catalyst::Plugin::Authentication - Infrastructure plugin for the Catalyst
222 authentication framework.
228 Authentication::Store::Foo
229 Authentication::Credential::Password
233 # ->login is provided by the Credential::Password module
234 $c->login('myusername', 'mypassword');
235 my $age = $c->user->age;
240 The authentication plugin provides generic user support. It is the basis
241 for both authentication (checking the user is who they claim to be), and
242 authorization (allowing the user to do what the system authorises them to do).
244 Using authentication is split into two parts. A Store is used to actually
245 store the user information, and can store any amount of data related to
246 the user. Multiple stores can be accessed from within one application.
247 Credentials are used to verify users, using the store, given data from
250 To implement authentication in a Catalyst application you need to add this
251 module, plus at least one store and one credential module.
253 Authentication data can also be stored in a session, if the application
254 is using the L<Catalyst::Plugin::Session> module.
258 =head2 The Authentication/Authorization Process
260 Web applications typically need to identify a user - to tell the user apart
261 from other users. This is usually done in order to display private information
262 that is only that user's business, or to limit access to the application so
263 that only certain entities can access certain parts.
265 This process is split up into several steps. First you ask the user to identify
266 themselves. At this point you can't be sure that the user is really who they
269 Then the user tells you who they are, and backs this claim with some piece of
270 information that only the real user could give you. For example, a password is
271 a secret that is known to both the user and you. When the user tells you this
272 password you can assume they're in on the secret and can be trusted (ignore
273 identity theft for now). Checking the password, or any other proof is called
274 B<credential verification>.
276 By this time you know exactly who the user is - the user's identity is
277 B<authenticated>. This is where this module's job stops, and other plugins step
278 in. The next logical step is B<authorization>, the process of deciding what a
279 user is (or isn't) allowed to do. For example, say your users are split into
280 two main groups - regular users and administrators. You should verify that the
281 currently logged in user is indeed an administrator before performing the
282 actions of an administrative part of your application. One way to do this is
283 with role based access control.
285 =head2 The Components In This Framework
287 =head3 Credential Verifiers
289 When user input is transferred to the L<Catalyst> application (typically via
290 form inputs) this data then enters the authentication framework through these
293 These plugins check the data, and ensure that it really proves the user is who
296 =head3 Storage Backends
298 The credentials also identify a user, and this family of modules is supposed to
299 take this identification data and return a standardized object oriented
300 representation of users.
302 When a user is retrieved from a store it is not necessarily authenticated.
303 Credential verifiers can either accept a user object, or fetch the object
304 themselves from the default store.
306 =head3 The Core Plugin
308 This plugin on its own is the glue, providing store registration, session
309 integration, and other goodness for the other plugins.
313 More layers of plugins can be stacked on top of the authentication code. For
314 example, L<Catalyst::Plugin::Session::PerUser> provides an abstraction of
315 browser sessions that is more persistent per users.
316 L<Catalyst::Plugin::Authorization::Roles> provides an accepted way to separate
317 and group users into categories, and then check which categories the current
322 Let's say we were storing users in an Apache style htpasswd file. Users are
323 stored in that file, with a hashed password and some extra comments. Users are
324 verified by supplying a password which is matched with the file.
326 This means that our application will begin like this:
332 Authentication::Credential::Password
333 Authentication::Store::Htpasswd
336 __PACKAGE__->config->{authentication}{htpasswd} = "passwdfile";
338 This loads the appropriate methods and also sets the htpasswd store as the
341 So, now that we have the code loaded we need to get data from the user into the
344 Let's create an authentication controller:
346 package MyApp::Controller::Auth;
349 my ( $self, $c ) = @_;
351 if ( my $user = $c->req->param("user")
352 and my $password = $c->req->param("password") )
354 if ( $c->login( $user, $password ) ) {
355 $c->res->body( "hello " . $c->user->name );
365 This code should be very readable. If all the necessary fields are supplied,
366 call the L<Authentication::Credential::Password/login> method on the
367 controller. If that succeeds the user is logged in.
369 It could be simplified though:
372 my ( $self, $c ) = @_;
379 Since the C<login> method knows how to find logically named parameters on its
382 The credential verifier will ask the default store to get the user whose ID is
383 the user parameter. In this case the default store is the htpasswd one. Once it
384 fetches the user from the store the password is checked and if it's OK
385 C<< $c->user >> will contain the user object returned from the htpasswd store.
387 We can also pass a user object to the credential verifier manually, if we have
388 several stores per app. This is discussed in
389 L<Catalyst::Plugin::Authentication::Store>.
391 Now imagine each admin user has a comment set in the htpasswd file saying
394 A restricted action might look like this:
396 sub restricted : Local {
397 my ( $self, $c ) = @_;
399 $c->detach("unauthorized")
400 unless $c->user_exists
401 and $c->user->extra_info() eq "admin";
403 # do something restricted here
406 This is somewhat similar to role based access control.
407 L<Catalyst::Plugin::Authentication::Store::Htpasswd> treats the extra info
408 field as a comma separated list of roles if it's treated that way. Let's
409 leverage this. Add the role authorization plugin:
416 sub restricted : Local {
417 my ( $self, $c ) = @_;
419 $c->detach("unauthorized") unless $c->check_roles("admin");
421 # do something restricted here
424 This is somewhat simpler and will work if you change your store, too, since the
425 role interface is consistent.
427 Let's say your app grew, and you now have 10000 users. It's no longer efficient
428 to maintain an htpasswd file, so you move this data to a database.
432 Authentication::Credential::Password
433 Authentication::Store::DBIC
437 __PACKAGE__->config->{authentication}{dbic} = ...; # see the DBIC store docs
439 The rest of your code should be unchanged. Now let's say you are integrating
440 typekey authentication to your system. For simplicity's sake we'll assume that
441 the user's are still keyed in the same way.
445 Authentication::Credential::Password
446 Authentication::Credential::TypeKey
447 Authentication::Store::DBIC
451 And in your auth controller add a new action:
453 sub typekey : Local {
454 my ( $self, $c ) = @_;
456 if ( $c->authenticate_typekey) { # uses $c->req and Authen::TypeKey
457 # same stuff as the $c->login method
462 You've now added a new credential verification mechanizm orthogonally to the
463 other components. All you have to do is make sure that the credential verifiers
464 pass on the same types of parameters to the store in order to retrieve user
473 Returns the currently logged in user or undef if there is none.
477 Whether or not a user is logged in right now.
479 The reason this method exists is that C<< $c->user >> may needlessly load the
480 user from the auth store.
482 If you're just going to say
484 if ( $c->user_exists ) {
487 $c->forward("login");
490 it should be more efficient than C<< $c->user >> when a user is marked in the
491 session but C<< $c->user >> hasn't been called yet.
495 Delete the currently logged in user from C<user> and the session.
499 Fetch a particular users details, defined by the given ID, via the default store.
509 Whether or not to store the user's logged in state in the session, if the
510 application is also using the L<Catalyst::Plugin::Session> plugin. This
511 value is set to true per default.
515 If multiple stores are being used, set the module you want as default here.
519 If multiple stores are being used, you need to provide a name for each store
520 here, as a hash, the keys are the names you wish to use, and the values are
521 the the names of the plugins.
524 __PACKAGE__->config( authentication => {
525 store => 'Catalyst::Plugin::Authentication::Store::HtPasswd',
527 'dbic' => 'Catalyst::Plugin::Authentication::Store::DBIC'
533 =head1 METHODS FOR STORE MANAGEMENT
537 =item default_auth_store
539 Return the store whose name is 'default'.
541 This is set to C<< $c->config->{authentication}{store} >> if that value exists,
542 or by using a Store plugin:
544 use Catalyst qw/Authentication Authentication::Store::Minimal/;
546 Sets the default store to
547 L<Catalyst::Plugin::Authentication::Store::Minimal::Backend>.
550 =item get_auth_store $name
552 Return the store whose name is $name.
554 =item get_auth_store_name $store
556 Return the name of the store $store.
560 A hash keyed by name, with the stores registered in the app.
562 =item auth_store_names
564 A ref-hash keyed by store, which contains the names of the stores.
566 =item register_auth_stores %stores_by_name
568 Register stores into the application.
572 =head1 INTERNAL METHODS
576 =item set_authenticated $user
578 Marks a user as authenticated. Should be called from a
579 C<Catalyst::Plugin::Authentication::Credential> plugin after successful
582 This involves setting C<user> and the internal data in C<session> if
583 L<Catalyst::Plugin::Session> is loaded.
585 =item auth_restore_user $user
587 Used to restore a user from the session, by C<user> only when it's actually
590 =item save_user_in_session $user
592 Used to save the user in a session.
596 Revives a user from the session object if there is one.
600 Sets the default configuration parameters.
608 This list might not be up to date.
610 =head2 User Storage Backends
612 L<Catalyst::Plugin::Authentication::Store::Minimal>,
613 L<Catalyst::Plugin::Authentication::Store::Htpasswd>,
614 L<Catalyst::Plugin::Authentication::Store::DBIC> (also works with Class::DBI).
616 =head2 Credential verification
618 L<Catalyst::Plugin::Authentication::Credential::Password>,
619 L<Catalyst::Plugin::Authentication::Credential::HTTP>,
620 L<Catalyst::Plugin::Authentication::Credential::TypeKey>
624 L<Catalyst::Plugin::Authorization::ACL>,
625 L<Catalyst::Plugin::Authorization::Roles>
627 =head2 Internals Documentation
629 L<Catalyst::Plugin::Authentication::Store>
633 L<Catalyst::Plugin::Session>,
634 L<Catalyst::Plugin::Session::PerUser>
636 =head1 DON'T SEE ALSO
638 This module along with its sub plugins deprecate a great number of other
639 modules. These include L<Catalyst::Plugin::Authentication::Simple>,
640 L<Catalyst::Plugin::Authentication::CDBI>.
642 At the time of writing these plugins have not yet been replaced or updated, but
643 should be eventually: L<Catalyst::Plugin::Authentication::OpenID>,
644 L<Catalyst::Plugin::Authentication::LDAP>,
645 L<Catalyst::Plugin::Authentication::CDBI::Basic>,
646 L<Catalyst::Plugin::Authentication::Basic::Remote>.
650 Yuval Kogman, C<nothingmuch@woobling.org>
656 =head1 COPYRIGHT & LICENSE
658 Copyright (c) 2005 the aforementioned authors. All rights
659 reserved. This program is free software; you can redistribute
660 it and/or modify it under the same terms as Perl itself.