3 Catalyst::Manual::Tutorial::Authentication - Catalyst Tutorial - Part 4: Authentication
8 This is B<Part 4 of 9> for the Catalyst tutorial.
10 L<Tutorial Overview|Catalyst::Manual::Tutorial>
16 L<Introduction|Catalyst::Manual::Tutorial::Intro>
20 L<Catalyst Basics|Catalyst::Manual::Tutorial::CatalystBasics>
24 L<Basic CRUD|Catalyst::Manual::Tutorial_BasicCRUD>
32 L<Authorization|Catalyst::Manual::Tutorial::Authorization>
36 L<Debugging|Catalyst::Manual::Tutorial::Debugging>
40 L<Testing|Catalyst::Manual::Tutorial::Testing>
44 L<AdvancedCRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
48 L<Appendices|Catalyst::Manual::Tutorial::Appendicies>
55 Now that we finally have a simple yet functional application, we can
56 focus on providing authentication (with authorization coming next in
59 This part of the tutorial is divided into two main sections: 1) basic,
60 cleartext authentication and 2) hash-based authentication.
62 B<TIP>: Note that all of the code for this part of the tutorial can be
63 pulled from the Catalyst Subversion repository in one step with the
66 svn checkout http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/Tutorial@###
67 IMPORTANT: Does not work yet. Will be completed for final version.
70 =head1 BASIC AUTHENTICATION
72 This section explores how to add authentication logic to a Catalyst
76 =head2 Add Users and Roles to the Database
78 First, we add both user and role information to the database (we will
79 add the role information here although it will not be used until the
80 authorization section, Part 5). Create a new SQL script file by opening
81 C<myapp02.sql> in your editor and insert:
84 -- Add users and roles tables, along with a many-to-many join table
87 id INTEGER PRIMARY KEY,
96 id INTEGER PRIMARY KEY,
99 CREATE TABLE user_roles (
102 PRIMARY KEY (user_id, role_id)
105 -- Load up some initial test data
107 INSERT INTO users VALUES (1, 'test01', 'mypass', 't01@na.com', 'Joe', 'Blow', 1);
108 INSERT INTO users VALUES (2, 'test02', 'mypass', 't02@na.com', 'Jane', 'Doe', 1);
109 INSERT INTO users VALUES (3, 'test03', 'mypass', 't03@na.com', 'No', 'Go', 0);
110 INSERT INTO roles VALUES (1, 'user');
111 INSERT INTO roles VALUES (2, 'admin');
112 INSERT INTO user_roles VALUES (1, 1);
113 INSERT INTO user_roles VALUES (1, 2);
114 INSERT INTO user_roles VALUES (2, 1);
115 INSERT INTO user_roles VALUES (3, 1);
117 Then load this into the C<myapp.db> database with the following command:
119 $ sqlite3 myapp.db < myapp02.sql
122 =head2 Add User and Role Information to DBIC Schema
124 This step adds DBIC-based classes for the user-related database tables
125 (the role information will not be used until Part 5):
127 Edit C<lib/MyAppDB.pm> and update the contents to match (only the
128 C<MyAppDB =E<gt> [qw/Book BookAuthor Author User UserRole Role/]> line
135 MyAppDB -- DBIC Schema Class
139 # Our schema needs to inherit from 'DBIx::Class::Schema'
140 use base qw/DBIx::Class::Schema/;
142 # Need to load the DB Model classes here.
143 # You can use this syntax if you want:
144 # __PACKAGE__->load_classes(qw/Book BookAuthor Author User UserRole Role/);
145 # Also, if you simply want to load all of the classes in a directory
146 # of the same name as your schema class (as we do here) you can use:
147 # __PACKAGE__->load_classes(qw//);
148 # But the variation below is more flexible in that it can be used to
149 # load from multiple namespaces.
150 __PACKAGE__->load_classes({
151 MyAppDB => [qw/Book BookAuthor Author User UserRole Role/]
157 =head2 Create New "Result Source Objects"
159 Create the following three files with the content shown below.
161 C<lib/MyAppDB/User.pm>:
163 package MyAppDB::User;
165 use base qw/DBIx::Class/;
167 # Load required DBIC stuff
168 __PACKAGE__->load_components(qw/PK::Auto Core/);
170 __PACKAGE__->table('users');
171 # Set columns in table
172 __PACKAGE__->add_columns(qw/id username password email_address first_name last_name/);
173 # Set the primary key for the table
174 __PACKAGE__->set_primary_key('id');
182 # 1) Name of relationship, DBIC will create accessor with this name
183 # 2) Name of the model class referenced by this relationship
184 # 3) Column name in *foreign* table
185 __PACKAGE__->has_many(map_user_role => 'MyAppDB::UserRole', 'user_id');
190 MyAppDB::User - A model object representing a person with access to the system.
194 This is an object that represents a row in the 'users' table of your application
195 database. It uses DBIx::Class (aka, DBIC) to do ORM.
197 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
198 Offline utilities may wish to use this class directly.
205 C<lib/MyAppDB/Role.pm>:
207 package MyAppDB::Role;
209 use base qw/DBIx::Class/;
211 # Load required DBIC stuff
212 __PACKAGE__->load_components(qw/PK::Auto Core/);
214 __PACKAGE__->table('roles');
215 # Set columns in table
216 __PACKAGE__->add_columns(qw/id role/);
217 # Set the primary key for the table
218 __PACKAGE__->set_primary_key('id');
226 # 1) Name of relationship, DBIC will create accessor with this name
227 # 2) Name of the model class referenced by this relationship
228 # 3) Column name in *foreign* table
229 __PACKAGE__->has_many(map_user_role => 'MyAppDB::UserRole', 'role_id');
234 MyAppDB::Role - A model object representing a class of access permissions to
239 This is an object that represents a row in the 'roles' table of your
240 application database. It uses DBIx::Class (aka, DBIC) to do ORM.
242 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
243 "Offline" utilities may wish to use this class directly.
250 C<lib/MyAppDB/UserRole.pm>:
252 package MyAppDB::UserRole;
254 use base qw/DBIx::Class/;
256 # Load required DBIC stuff
257 __PACKAGE__->load_components(qw/PK::Auto Core/);
259 __PACKAGE__->table('user_roles');
260 # Set columns in table
261 __PACKAGE__->add_columns(qw/user_id role_id/);
262 # Set the primary key for the table
263 __PACKAGE__->set_primary_key(qw/user_id role_id/);
271 # 1) Name of relationship, DBIC will create accessor with this name
272 # 2) Name of the model class referenced by this relationship
273 # 3) Column name in *this* table
274 __PACKAGE__->belongs_to(user => 'MyAppDB::User', 'user_id');
278 # 1) Name of relationship, DBIC will create accessor with this name
279 # 2) Name of the model class referenced by this relationship
280 # 3) Column name in *this* table
281 __PACKAGE__->belongs_to(role => 'MyAppDB::Role', 'role_id');
286 MyAppDB::UserRole - A model object representing the JOIN between Users and Roles.
290 This is an object that represents a row in the 'user_roles' table of your application
291 database. It uses DBIx::Class (aka, DBIC) to do ORM.
293 You probably won't need to use this class directly -- it will be automatically
294 used by DBIC where joins are needed.
296 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
297 Offline utilities may wish to use this class directly.
303 The code for these three result source classes is obviously very familiar to the C<Book>, C<Author>, and C<BookAuthor> classes created in Part 2.
306 =head2 Sanity-Check Reload of Development Server
308 We aren't ready to try out the authentication just yet; we only want to do a quick check to be sure our model loads correctly. Press C<Ctrl-C> to kill the previous server instance (if it's still running) and restart it:
310 $ script/myapp_server.pl
312 Look for the three new model objects in the startup debug output:
315 .-------------------------------------------------------------------+----------.
317 +-------------------------------------------------------------------+----------+
318 | MyApp::Controller::Books | instance |
319 | MyApp::Controller::Root | instance |
320 | MyApp::Model::MyAppDB | instance |
321 | MyApp::Model::MyAppDB::Author | class |
322 | MyApp::Model::MyAppDB::Book | class |
323 | MyApp::Model::MyAppDB::BookAuthor | class |
324 | MyApp::Model::MyAppDB::Role | class |
325 | MyApp::Model::MyAppDB::User | class |
326 | MyApp::Model::MyAppDB::UserRole | class |
327 | MyApp::View::TT | instance |
328 '-------------------------------------------------------------------+----------'
331 Again, notice that your "result source" classes have been "re-loaded" by Catalyst under C<MyApp::Model>.
334 =head2 Include Authentication and Session Plugins
336 Edit C<lib/MyApp.pm> and update it as follows (everything below C<DefaultEnd> is new):
347 Authentication::Store::DBIC
348 Authentication::Credential::Password
351 Session::Store::FastMmap
352 Session::State::Cookie
355 The three C<Authentication> plugins work together to support
356 Authentication while the C<Session> plugins are required to maintain
357 state across multiple HTTP requests. Note that there are several
358 options for L<Session::Store|Catalyst::Plugin::Session::Store>
359 (L<Session::Store::FastMmap|Catalyst::Plugin::Session::Store::FastMmap>
360 is generally a good choice if you are on Unix; try
361 L<Cache::FileCache|Catalyst::Plugin::Cache::FileCache> if you are on
362 Win32) -- consult L<Session::Store|Catalyst::Plugin::Session::Store> and
363 its subclasses for additional information.
366 =head2 Configure Authentication
368 Although C<__PACKAGE__-E<gt>config(name =E<gt> 'value');> is still
369 supported, newer Catalyst applications tend to place all configuration
370 information in C<myapp.yml> and automatically load this information into
371 C<MyApp-E<gt>config> using the
372 L<ConfigLoader|Catalyst::Plugin::ConfigLoader> plugin. Here, we need
373 to load several parameters that tell
374 L<Catalyst::Plugin::Authentication|Catalyst::Plugin::Authentication>
375 where to locate information in your database. To do this, edit the
376 C<myapp.yml> YAML and update it to match:
382 # Note this first definition would be the same as setting
383 # __PACKAGE__->config->{authentication}->{dbic}->{user_class} = 'MyAppDB::User'
384 # in lib/MyApp.pm (IOW, each hash key becomes a "name:" in the YAML file).
386 # This is the model object created by Catalyst::Model::DBIC from your
387 # schema (you created 'MyAppDB::User' but as the Catalyst startup
388 # debug messages show, it was loaded as 'MyApp::Model::MyAppDB::User').
389 # NOTE: Omit 'MyApp::Model' to avoid a component lookup issue in Catalyst 5.66
390 user_class: MyAppDB::User
391 # This is the name of the field in your 'users' table that contains the user's name
393 # This is the name of the field in your 'users' table that contains the password
394 password_field: password
395 # Other options can go here for hashed passwords
397 Inline comments in the code above explain how each field is being used.
399 B<TIP>: Although YAML uses a very simple and easy-to-ready format, it
400 does require the use of a consistent level of indenting. Be sure you
401 line up everything on a given 'level' with the same number of indents.
402 Also, be sure not to use C<tab> characters (YAML does not support them
403 because they are handled inconsistently across editors).
406 =head2 Add Login and Logout Controllers
408 Use the Catalyst create script to create two stub controller files:
410 $ script/myapp_create.pl controller Login
411 $ script/myapp_create.pl controller Logout
413 B<NOTE>: You could easily use a single controller here. For example,
414 you could have a C<User> controller with both C<login> and C<logout>
415 actions. Remember, Catalyst is designed to be very flexible, and leaves
416 such matters up to you, the designer and programmer.
418 Then open C<lib/MyApp/Controller/Login.pm> and add:
426 sub base :Path :Args(0) {
429 # Get the username and password from form
430 my $username = $c->request->params->{username} || "";
431 my $password = $c->request->params->{password} || "";
433 # If the username and password values were found in form
434 if ($username && $password) {
435 # Attempt to log the user in
436 if ($c->login($username, $password)) {
437 # If successful, then let them use the application
438 $c->response->redirect($c->uri_for('/books/list'));
441 # Set an error message
442 $c->stash->{error_msg} = "Bad username or password.";
446 # If either of above don't work out, send to the login page
447 $c->stash->{template} = 'login.tt2';
450 This controller fetches the C<username> and C<password> values from the
451 login form and attempts to perform a login. If successful, it redirects
452 the user to the book list page. If the login fails, the user will stay
453 at the login page but receive an error message. If the C<username> and
454 C<password> values are not present in the form, the user will be taken
455 to the empty login form.
457 We are using C<sub base :Path :Args(0) {...}> here to specifically match
458 the URL C</login>. C<Path> actions (aka, "literal actions") create URI
459 matches relative to the namespace of the controller where they are defined.
460 Although C<Path> supports arguments that allow relative and absolute paths
461 to be defined, here we use an empty C<Path> definition to match on just the
462 name of the controller itself. The method name, C<base>, is arbitrary.
463 We make the match even more specific with the C<:Args(0)> action modifier
464 -- this forces the match on I<only> C</login>, not C</login/somethingelse>.
466 Note that we could have used something like C<sub default :Private>;
467 however, the use of C<default> actions is discouraged because it does
468 not receive path args as with other actions. The recommended practice
469 is to only use C<default> in C<MyApp::Controller::Root>.
471 Next, create a corresponding method in C<lib/MyApp/Controller/Logout.pm>:
479 sub base :Path :Args(0) {
482 # Clear the user's state
485 # Send the user to the starting point
486 $c->response->redirect($c->uri_for('/'));
489 Note that we are using the same C<sub base :Path :Args(0) {...}> style
490 of action as with the login logic.
493 =head2 Add a Login Form TT Template Page
495 Create a login form by opening C<root/src/login.tt2> and inserting:
497 [% META title = 'Login' %]
500 <form method="post" action=" [% Catalyst.uri_for('/login') %] ">
504 <td><input type="text" name="username" size="40" /></td>
508 <td><input type="password" name="password" size="40" /></td>
511 <td colspan="2"><input type="submit" name="submit" value="Submit" /></td>
517 =head2 Add Valid User Check
519 We need something that provides enforcement for the authentication
520 mechanism -- a I<global> mechanism that prevents users who have not
521 passed authentication from reaching any pages except the login page.
522 This is generally done via an C<auto> action/method (prior to Catalyst
523 v5.66, this sort of thing would go in C<MyApp.pm>, but starting in
524 v5.66, the preferred location is C<lib/MyApp/Controller/Root.pm>).
526 Edit the existing C<lib/MyApp/Controller/Root.pm> class file and insert
527 the following method:
531 Check if there is a user and, if not, forward to login page
535 # Note that 'auto' runs after 'begin' but before your actions and that
536 # 'auto' "chain" (all from application path to most specific class are run)
540 # Allow unauthenticated users to reach the login page
541 if ($c->request->path =~ /login/) {
545 # If a user doesn't exist, force login
546 if (!$c->user_exists) {
547 # Dump a log message to the development server debug output
548 $c->log->debug('***Root::auto User not found, forwarding to /login');
549 # Redirect the user to the login page
550 $c->response->redirect($c->uri_for('/login'));
551 # Return 0 to cancel 'post-auto' processing and prevent use of application
555 # User found, so return 1 to continue with processing after this 'auto'
559 B<Note:> Catalyst provides a number of different types of actions, such
560 as C<Local>, C<Regex>, and C<Private>. You should refer to
561 L<Catalyst::Manual::Intro> for a more detailed explanation, but the
562 following bullet points provide a quick introduction:
568 The majority of application use C<Local> actions for items that respond
569 to user requests and C<Private> actions for those that do not directly
570 respond to user input.
574 There are five types of C<Private> actions: C<begin>, C<end>,
575 C<default>, C<index>, and C<auto>.
579 Unlike the other actions where only a single method is called for each
580 request, I<every> auto action along the chain of namespaces will be
585 By placing the authentication enforcement code inside the C<auto> method
586 of C<lib/MyApp/Controller/Root.pm> (or C<lib/MyApp.pm>), it will be
587 called for I<every> request that is received by the entire application.
590 =head2 Displaying Content Only to Authenticated Users
592 Let's say you want to provide some information on the login page that
593 changes depending on whether the user has authenticated yet. To do
594 this, open C<root/src/login.tt2> in your editor and add the following
595 lines to the bottom of the file:
599 # This code illustrates how certain parts of the TT
600 # template will only be shown to users who have logged in
602 [% IF Catalyst.user %]
603 Please Note: You are already logged in as '[% Catalyst.user.username %]'.
604 You can <a href="[% Catalyst.uri_for('/logout') %]">logout</a> here.
606 You need to log in to use this application.
609 Note that this whole block is a comment because the "#" appears
610 immediate after the "[%" (with no spaces in between). Although it
611 can be a handy way to temporarily "comment out" a whole block of
612 TT code, it's probably a little too subtle for use in "normal"
616 Although most of the code is comments, the middle few lines provide a
617 "you are already logged in" reminder if the user returns to the login
618 page after they have already authenticated. For users who have not yet
619 authenticated, a "You need to log in..." message is displayed (note the
620 use of an IF-THEN-ELSE construct in TT).
623 =head2 Try Out Authentication
625 Press C<Ctrl-C> to kill the previous server instance (if it's still
626 running) and restart it:
628 $ script/myapp_server.pl
630 B<IMPORTANT NOTE>: If you happen to be using Internet Explorer, you may
631 need to use the command C<script/myapp_server.pl -k> to enable the
632 keepalive feature in the development server. Otherwise, the HTTP
633 redirect on successful login may not work correctly with IE (it seems to
634 work without -k if you are running the web browser and development
635 server on the same machine). If you are using browser a browser other
636 than IE, it should work either way. If you want to make keepalive the
637 default, you can edit C<script/myapp_server.pl> and change the
638 initialization value for C<$keepalive> to C<1>. (You will need to do
639 this every time you create a new Catalyst application or rebuild the
640 C<myapp_server.pl> script.)
642 Now trying going to L<http://localhost:3000/books/list> and you should
643 be redirected to the login page, hitting Shift+Reload if necessary (the
644 "You are already logged in" message should I<not> appear -- if it does,
645 click the C<logout> button and try again). Note the C<***Root::auto User
646 not found...> debug message in the development server output. Enter
647 username C<test01> and password C<mypass>, and you should be taken to
650 Open C<root/src/books/list.tt2> and add the following lines to the
654 <a href="[% Catalyst.uri_for('/login') %]">Login</a>
655 <a href="[% Catalyst.uri_for('form_create') %]">Create</a>
658 Reload your browser and you should now see a "Login" and "Create" links
659 at the bottom of the page (as mentioned earlier, you can update
660 template files without reloading the development server). Click this
661 link to return to the login page. This time you I<should> see the
662 "You are already logged in" message.
664 Finally, click the C<You can logout here> link on the C</login> page.
665 You should stay at the login page, but the message should change to "You
666 need to log in to use this application."
669 =head1 USING PASSWORD HASHES
671 In this section we increase the security of our system by converting
672 from cleartext passwords to SHA-1 password hashes.
674 B<Note:> This section is optional. You can skip it and the rest of the
675 tutorial will function normally.
677 Note that even with the techniques shown in this section, the browser
678 still transmits the passwords in cleartext to your application. We are
679 just avoiding the I<storage> of cleartext passwords in the database by
680 using a SHA-1 hash. If you are concerned about cleartext passwords
681 between the browser and your application, consider using SSL/TLS, made
682 easy with the Catalyst plugin
683 L<Catalyst::Plugin:RequireSSL|Catalyst::Plugin:RequireSSL>.
686 =head2 Get a SHA-1 Hash for the Password
688 Catalyst uses the C<Digest> module to support a variety of hashing
689 algorithms. Here we will use SHA-1 (SHA = Secure Hash Algorithm).
690 First, we should compute the SHA-1 hash for the "mypass" password we are
691 using. The following command-line Perl script provides a "quick and
692 dirty" way to do this:
694 $ perl -MDigest::SHA -e 'print Digest::SHA::sha1_hex("mypass"), "\n"'
695 e727d1464ae12436e899a726da5b2f11d8381b26
698 B<Note:> You should probably modify this code for production use to
699 not read the password from the command line. By having the script
700 prompt for the cleartext password, it avoids having the password linger
701 in forms such as your C<.bash_history> files (assuming you are using
702 BASH as your shell). An example of such a script can be found in
706 =head2 Switch to SHA-1 Password Hashes in the Database
708 Next, we need to change the C<password> column of our C<users> table to
709 store this hash value vs. the existing cleartext password. Open
710 C<myapp03.sql> in your editor and enter:
713 -- Convert passwords to SHA-1 hashes
715 UPDATE users SET password = 'e727d1464ae12436e899a726da5b2f11d8381b26' WHERE id = 1;
716 UPDATE users SET password = 'e727d1464ae12436e899a726da5b2f11d8381b26' WHERE id = 2;
717 UPDATE users SET password = 'e727d1464ae12436e899a726da5b2f11d8381b26' WHERE id = 3;
719 Then use the following command to update the SQLite database:
721 $ sqlite3 myapp.db < myapp03.sql
723 B<Note:> We are using SHA-1 hashes here, but many other hashing
724 algorithms are supported. See C<Digest> for more information.
727 =head2 Enable SHA-1 Hash Passwords in
728 C<Catalyst::Plugin::Authentication::Store::DBIC>
730 Edit C<myapp.yml> and update it to match (the C<password_type> and
731 C<password_hash_type> are new, everything else is the same):
737 # Note this first definition would be the same as setting
738 # __PACKAGE__->config->{authentication}->{dbic}->{user_class} = 'MyAppDB::User'
739 # in lib/MyApp.pm (IOW, each hash key becomes a "name:" in the YAML file).
741 # This is the model object created by Catalyst::Model::DBIC from your
742 # schema (you created 'MyAppDB::User' but as the Catalyst startup
743 # debug messages show, it was loaded as 'MyApp::Model::MyAppDB::User').
744 # NOTE: Omit 'MyApp::Model' to avoid a component lookup issue in Catalyst 5.66
745 user_class: MyAppDB::User
746 # This is the name of the field in your 'users' table that contains the user's name
748 # This is the name of the field in your 'users' table that contains the password
749 password_field: password
750 # Other options can go here for hashed passwords
751 # Enabled hashed passwords
752 password_type: hashed
753 # Use the SHA-1 hashing algorithm
754 password_hash_type: SHA-1
757 =head2 Try Out the Hashed Passwords
759 Press C<Ctrl-C> to kill the previous server instance (if it's still
760 running) and restart it:
762 $ script/myapp_server.pl
764 You should now be able to go to L<http://localhost:3000/books/list> and
765 login as before. When done, click the "Logout" link on the login page
766 (or point your browser at L<http://localhost:3000/logout>).
771 Kennedy Clark, C<hkclark@gmail.com>
773 Please report any errors, issues or suggestions to the author. The
774 most recent version of the Catlayst Tutorial can be found at
775 L<http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/>.
777 Copyright 2006, Kennedy Clark, under Creative Commons License
778 (L<http://creativecommons.org/licenses/by-nc-sa/2.5/>).