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.08";
27 sub set_authenticated {
28 my ( $c, $user ) = @_;
31 $c->request->{user} = $user; # compatibility kludge
33 if ( $c->isa("Catalyst::Plugin::Session")
34 and $c->config->{authentication}{use_session}
35 and $user->supports("session") )
37 $c->save_user_in_session($user);
40 $c->NEXT::set_authenticated($user);
50 if ( defined(my $user = $c->_user) ) {
53 return $c->auth_restore_user;
59 return defined($c->_user) || defined($c->_user_in_session);
62 sub save_user_in_session {
63 my ( $c, $user ) = @_;
65 my $store = $user->store || ref $user;
66 $c->session->{__user_store} = $c->get_auth_store_name($store) || $store;
67 $c->session->{__user} = $user->for_session;
76 $c->isa("Catalyst::Plugin::Session")
77 and $c->config->{authentication}{use_session}
78 and $c->session_is_valid
80 delete @{ $c->session }{qw/__user __user_store/};
87 my ( $c, $uid, @rest ) = @_;
89 if ( my $store = $c->default_auth_store ) {
90 return $store->get_user( $uid, @rest );
93 Catalyst::Exception->throw(
94 "The user id $uid was passed to an authentication "
95 . "plugin, but no default store was specified" );
99 sub _user_in_session {
103 $c->isa("Catalyst::Plugin::Session")
104 and $c->config->{authentication}{use_session}
105 and $c->session_is_valid;
107 return $c->session->{__user};
112 sub auth_restore_user {
113 my ( $c, $frozen_user, $store_name ) = @_;
115 $frozen_user ||= $c->_user_in_session;
116 return unless defined($frozen_user);
118 $store_name ||= $c->session->{__user_store};
120 my $store = $c->get_auth_store($store_name);
121 $c->_user( my $user = $store->from_session( $c, $frozen_user ) );
130 my $cfg = $c->config->{authentication} || {};
137 $c->register_auth_stores(
138 default => $cfg->{store},
139 %{ $cfg->{stores} || {} },
146 my ( $self, $name ) = @_;
147 $self->auth_stores->{$name} || ( Class::Inspector->loaded($name) && $name );
150 sub get_auth_store_name {
151 my ( $self, $store ) = @_;
152 $self->auth_store_names->{$store};
155 sub register_auth_stores {
156 my ( $self, %new ) = @_;
158 foreach my $name ( keys %new ) {
159 my $store = $new{$name} or next;
160 $self->auth_stores->{$name} = $store;
161 $self->auth_store_names->{$store} = $name;
167 $self->_auth_stores(@_) || $self->_auth_stores( {} );
170 sub auth_store_names {
173 $self->_auth_store_names || do {
174 tie my %hash, 'Tie::RefHash';
175 $self->_auth_store_names( \%hash );
179 sub default_auth_store {
182 if ( my $new = shift ) {
183 $self->register_auth_stores( default => $new );
186 $self->get_auth_store("default");
197 Catalyst::Plugin::Authentication - Infrastructure plugin for the Catalyst
198 authentication framework.
204 Authentication::Store::Foo
205 Authentication::Credential::Password
209 # ->login is provided by the Credential::Password module
210 $c->login('myusername', 'mypassword');
211 my $age = $c->user->age;
216 The authentication plugin provides generic user support. It is the basis
217 for both authentication (checking the user is who they claim to be), and
218 authorization (allowing the user to do what the system authorises them to do).
220 Using authentication is split into two parts. A Store is used to actually
221 store the user information, and can store any amount of data related to
222 the user. Multiple stores can be accessed from within one application.
223 Credentials are used to verify users, using the store, given data from
226 To implement authentication in a Catalyst application you need to add this
227 module, plus at least one store and one credential module.
229 Authentication data can also be stored in a session, if the application
230 is using the L<Catalyst::Plugin::Session> module.
234 =head2 The Authentication/Authorization Process
236 Web applications typically need to identify a user - to tell the user apart
237 from other users. This is usually done in order to display private information
238 that is only that user's business, or to limit access to the application so
239 that only certain entities can access certain parts.
241 This process is split up into several steps. First you ask the user to identify
242 themselves. At this point you can't be sure that the user is really who they
245 Then the user tells you who they are, and backs this claim with some piece of
246 information that only the real user could give you. For example, a password is
247 a secret that is known to both the user and you. When the user tells you this
248 password you can assume they're in on the secret and can be trusted (ignore
249 identity theft for now). Checking the password, or any other proof is called
250 B<credential verification>.
252 By this time you know exactly who the user is - the user's identity is
253 B<authenticated>. This is where this module's job stops, and other plugins step
254 in. The next logical step is B<authorization>, the process of deciding what a
255 user is (or isn't) allowed to do. For example, say your users are split into
256 two main groups - regular users and administrators. You should verify that the
257 currently logged in user is indeed an administrator before performing the
258 actions of an administrative part of your application. One way to do this is
259 with role based access control.
261 =head2 The Components In This Framework
263 =head3 Credential Verifiers
265 When user input is transferred to the L<Catalyst> application (typically via
266 form inputs) this data then enters the authentication framework through these
269 These plugins check the data, and ensure that it really proves the user is who
272 =head3 Storage Backends
274 The credentials also identify a user, and this family of modules is supposed to
275 take this identification data and return a standardized object oriented
276 representation of users.
278 When a user is retrieved from a store it is not necessarily authenticated.
279 Credential verifiers can either accept a user object, or fetch the object
280 themselves from the default store.
282 =head3 The Core Plugin
284 This plugin on its own is the glue, providing store registration, session
285 integration, and other goodness for the other plugins.
289 More layers of plugins can be stacked on top of the authentication code. For
290 example, L<Catalyst::Plugin::Session::PerUser> provides an abstraction of
291 browser sessions that is more persistent per users.
292 L<Catalyst::Plugin::Authorization::Roles> provides an accepted way to separate
293 and group users into categories, and then check which categories the current
298 Let's say we were storing users in an Apache style htpasswd file. Users are
299 stored in that file, with a hashed password and some extra comments. Users are
300 verified by supplying a password which is matched with the file.
302 This means that our application will begin like this:
308 Authentication::Credential::Password
309 Authentication::Store::Htpasswd
312 __PACKAGE__->config->{authentication}{htpasswd} = "passwdfile";
314 This loads the appropriate methods and also sets the htpasswd store as the
317 So, now that we have the code loaded we need to get data from the user into the
320 Let's create an authentication controller:
322 package MyApp::Controller::Auth;
325 my ( $self, $c ) = @_;
327 if ( my $user = $c->req->param("user")
328 and my $password = $c->req->param("password") )
330 if ( $c->login( $user, $password ) ) {
331 $c->res->body( "hello " . $c->user->name );
341 This code should be very readable. If all the necessary fields are supplied,
342 call the L<Authentication::Credential::Password/login> method on the
343 controller. If that succeeds the user is logged in.
345 It could be simplified though:
348 my ( $self, $c ) = @_;
355 Since the C<login> method knows how to find logically named parameters on its
358 The credential verifier will ask the default store to get the user whose ID is
359 the user parameter. In this case the default store is the htpasswd one. Once it
360 fetches the user from the store the password is checked and if it's OK
361 C<< $c->user >> will contain the user object returned from the htpasswd store.
363 We can also pass a user object to the credential verifier manually, if we have
364 several stores per app. This is discussed in
365 L<Catalyst::Plugin::Authentication::Store>.
367 Now imagine each admin user has a comment set in the htpasswd file saying
370 A restricted action might look like this:
372 sub restricted : Local {
373 my ( $self, $c ) = @_;
375 $c->detach("unauthorized")
376 unless $c->user_exists
377 and $c->user->extra_info() eq "admin";
379 # do something restricted here
382 This is somewhat similar to role based access control.
383 L<Catalyst::Plugin::Authentication::Store::Htpasswd> treats the extra info
384 field as a comma separated list of roles if it's treated that way. Let's
385 leverage this. Add the role authorization plugin:
392 sub restricted : Local {
393 my ( $self, $c ) = @_;
395 $c->detach("unauthorized") unless $c->check_roles("admin");
397 # do something restricted here
400 This is somewhat simpler and will work if you change your store, too, since the
401 role interface is consistent.
403 Let's say your app grew, and you now have 10000 users. It's no longer efficient
404 to maintain an htpasswd file, so you move this data to a database.
408 Authentication::Credential::Password
409 Authentication::Store::DBIC
413 __PACKAGE__->config->{authentication}{dbic} = ...; # see the DBIC store docs
415 The rest of your code should be unchanged. Now let's say you are integrating
416 typekey authentication to your system. For simplicity's sake we'll assume that
417 the user's are still keyed in the same way.
421 Authentication::Credential::Password
422 Authentication::Credential::TypeKey
423 Authentication::Store::DBIC
427 And in your auth controller add a new action:
429 sub typekey : Local {
430 my ( $self, $c ) = @_;
432 if ( $c->authenticate_typekey) { # uses $c->req and Authen::TypeKey
433 # same stuff as the $c->login method
438 You've now added a new credential verification mechanizm orthogonally to the
439 other components. All you have to do is make sure that the credential verifiers
440 pass on the same types of parameters to the store in order to retrieve user
449 Returns the currently logged in user or undef if there is none.
453 Whether or not a user is logged in right now.
455 The reason this method exists is that C<< $c->user >> may needlessly load the
456 user from the auth store.
458 If you're just going to say
460 if ( $c->user_exists ) {
463 $c->forward("login");
466 it should be more efficient than C<< $c->user >> when a user is marked in the
467 session but C<< $c->user >> hasn't been called yet.
471 Delete the currently logged in user from C<user> and the session.
475 Fetch a particular users details, defined by the given ID, via the default store.
485 Whether or not to store the user's logged in state in the session, if the
486 application is also using the L<Catalyst::Plugin::Session> plugin. This
487 value is set to true per default.
491 If multiple stores are being used, set the module you want as default here.
495 If multiple stores are being used, you need to provide a name for each store
496 here, as a hash, the keys are the names you wish to use, and the values are
497 the the names of the plugins.
500 __PACKAGE__->config( authentication => {
501 store => 'Catalyst::Plugin::Authentication::Store::HtPasswd',
503 'dbic' => 'Catalyst::Plugin::Authentication::Store::DBIC'
509 =head1 METHODS FOR STORE MANAGEMENT
513 =item default_auth_store
515 Return the store whose name is 'default'.
517 This is set to C<< $c->config->{authentication}{store} >> if that value exists,
518 or by using a Store plugin:
520 use Catalyst qw/Authentication Authentication::Store::Minimal/;
522 Sets the default store to
523 L<Catalyst::Plugin::Authentication::Store::Minimal::Backend>.
526 =item get_auth_store $name
528 Return the store whose name is $name.
530 =item get_auth_store_name $store
532 Return the name of the store $store.
536 A hash keyed by name, with the stores registered in the app.
538 =item auth_store_names
540 A ref-hash keyed by store, which contains the names of the stores.
542 =item register_auth_stores %stores_by_name
544 Register stores into the application.
548 =head1 INTERNAL METHODS
552 =item set_authenticated $user
554 Marks a user as authenticated. Should be called from a
555 C<Catalyst::Plugin::Authentication::Credential> plugin after successful
558 This involves setting C<user> and the internal data in C<session> if
559 L<Catalyst::Plugin::Session> is loaded.
561 =item auth_restore_user $user
563 Used to restore a user from the session, by C<user> only when it's actually
566 =item save_user_in_session $user
568 Used to save the user in a session.
572 Revives a user from the session object if there is one.
576 Sets the default configuration parameters.
584 This list might not be up to date.
586 =head2 User Storage Backends
588 L<Catalyst::Plugin::Authentication::Store::Minimal>,
589 L<Catalyst::Plugin::Authentication::Store::Htpasswd>,
590 L<Catalyst::Plugin::Authentication::Store::DBIC> (also works with Class::DBI).
592 =head2 Credential verification
594 L<Catalyst::Plugin::Authentication::Credential::Password>,
595 L<Catalyst::Plugin::Authentication::Credential::HTTP>,
596 L<Catalyst::Plugin::Authentication::Credential::TypeKey>
600 L<Catalyst::Plugin::Authorization::ACL>,
601 L<Catalyst::Plugin::Authorization::Roles>
603 =head2 Internals Documentation
605 L<Catalyst::Plugin::Authentication::Store>
609 L<Catalyst::Plugin::Session>,
610 L<Catalyst::Plugin::Session::PerUser>
612 =head1 DON'T SEE ALSO
614 This module along with its sub plugins deprecate a great number of other
615 modules. These include L<Catalyst::Plugin::Authentication::Simple>,
616 L<Catalyst::Plugin::Authentication::CDBI>.
618 At the time of writing these plugins have not yet been replaced or updated, but
619 should be eventually: L<Catalyst::Plugin::Authentication::OpenID>,
620 L<Catalyst::Plugin::Authentication::LDAP>,
621 L<Catalyst::Plugin::Authentication::CDBI::Basic>,
622 L<Catalyst::Plugin::Authentication::Basic::Remote>.
626 Yuval Kogman, C<nothingmuch@woobling.org>
632 =head1 COPYRIGHT & LICENSE
634 Copyright (c) 2005 the aforementioned authors. All rights
635 reserved. This program is free software; you can redistribute
636 it and/or modify it under the same terms as Perl itself.