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
75 =head2 Add Users and Roles to the Database
77 First, we add both user and role information to the database (we will
78 add the role information here although it will not be used until the
79 authorization section, Part 5). Create a new SQL script file by opening
80 C<myapp02.sql> in your editor and insert:
83 -- Add users and roles tables, along with a many-to-many join table
86 id INTEGER PRIMARY KEY,
95 id INTEGER PRIMARY KEY,
98 CREATE TABLE user_roles (
101 PRIMARY KEY (user_id, role_id)
104 -- Load up some initial test data
106 INSERT INTO users VALUES (1, 'test01', 'mypass', 't01@na.com', 'Joe', 'Blow', 1);
107 INSERT INTO users VALUES (2, 'test02', 'mypass', 't02@na.com', 'Jane', 'Doe', 1);
108 INSERT INTO users VALUES (3, 'test03', 'mypass', 't03@na.com', 'No', 'Go', 0);
109 INSERT INTO roles VALUES (1, 'user');
110 INSERT INTO roles VALUES (2, 'admin');
111 INSERT INTO user_roles VALUES (1, 1);
112 INSERT INTO user_roles VALUES (1, 2);
113 INSERT INTO user_roles VALUES (2, 1);
114 INSERT INTO user_roles VALUES (3, 1);
116 Then load this into the C<myapp.db> database with the following command:
118 $ sqlite3 myapp.db < myapp02.sql
121 =head2 Add User and Role Information to DBIC Schema
123 This step adds DBIC-based classes for the user-related database tables
124 (the role information will not be used until Part 5):
126 Edit C<lib/MyAppDB.pm> and update the contents to match (only the
127 C<MyAppDB =E<gt> [qw/Book BookAuthor Author User UserRole Role/]> line
134 MyAppDB -- DBIC Schema Class
138 # Our schema needs to inherit from 'DBIx::Class::Schema'
139 use base qw/DBIx::Class::Schema/;
141 # Need to load the DB Model classes here.
142 # You can use this syntax if you want:
143 # __PACKAGE__->load_classes(qw/Book BookAuthor Author User UserRole Role/);
144 # Also, if you simply want to load all of the classes in a directory
145 # of the same name as your schema class (as we do here) you can use:
146 # __PACKAGE__->load_classes(qw//);
147 # But the variation below is more flexible in that it can be used to
148 # load from multiple namespaces.
149 __PACKAGE__->load_classes({
150 MyAppDB => [qw/Book BookAuthor Author User UserRole Role/]
156 =head2 Create New "Result Source Objects"
158 Create the following three files with the content shown below.
160 C<lib/MyAppDB/User.pm>:
162 package MyAppDB::User;
164 use base qw/DBIx::Class/;
166 # Load required DBIC stuff
167 __PACKAGE__->load_components(qw/PK::Auto Core/);
169 __PACKAGE__->table('users');
170 # Set columns in table
171 __PACKAGE__->add_columns(qw/id username password email_address first_name last_name/);
172 # Set the primary key for the table
173 __PACKAGE__->set_primary_key('id');
181 # 1) Name of relationship, DBIC will create accessor with this name
182 # 2) Name of the model class referenced by this relationship
183 # 3) Column name in *foreign* table
184 __PACKAGE__->has_many(map_user_role => 'MyAppDB::UserRole', 'user_id');
189 MyAppDB::User - A model object representing a person with access to the system.
193 This is an object that represents a row in the 'users' table of your application
194 database. It uses DBIx::Class (aka, DBIC) to do ORM.
196 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
197 Offline utilities may wish to use this class directly.
204 C<lib/MyAppDB/Role.pm>:
206 package MyAppDB::Role;
208 use base qw/DBIx::Class/;
210 # Load required DBIC stuff
211 __PACKAGE__->load_components(qw/PK::Auto Core/);
213 __PACKAGE__->table('roles');
214 # Set columns in table
215 __PACKAGE__->add_columns(qw/id role/);
216 # Set the primary key for the table
217 __PACKAGE__->set_primary_key('id');
225 # 1) Name of relationship, DBIC will create accessor with this name
226 # 2) Name of the model class referenced by this relationship
227 # 3) Column name in *foreign* table
228 __PACKAGE__->has_many(map_user_role => 'MyAppDB::UserRole', 'role_id');
233 MyAppDB::Role - A model object representing a class of access permissions to
238 This is an object that represents a row in the 'roles' table of your
239 application database. It uses DBIx::Class (aka, DBIC) to do ORM.
241 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
242 "Offline" utilities may wish to use this class directly.
249 C<lib/MyAppDB/UserRole.pm>:
251 package MyAppDB::UserRole;
253 use base qw/DBIx::Class/;
255 # Load required DBIC stuff
256 __PACKAGE__->load_components(qw/PK::Auto Core/);
258 __PACKAGE__->table('user_roles');
259 # Set columns in table
260 __PACKAGE__->add_columns(qw/user_id role_id/);
261 # Set the primary key for the table
262 __PACKAGE__->set_primary_key(qw/user_id role_id/);
270 # 1) Name of relationship, DBIC will create accessor with this name
271 # 2) Name of the model class referenced by this relationship
272 # 3) Column name in *this* table
273 __PACKAGE__->belongs_to(user => 'MyAppDB::User', 'user_id');
277 # 1) Name of relationship, DBIC will create accessor with this name
278 # 2) Name of the model class referenced by this relationship
279 # 3) Column name in *this* table
280 __PACKAGE__->belongs_to(role => 'MyAppDB::Role', 'role_id');
285 MyAppDB::UserRole - A model object representing the JOIN between Users and Roles.
289 This is an object that represents a row in the 'user_roles' table of your application
290 database. It uses DBIx::Class (aka, DBIC) to do ORM.
292 You probably won't need to use this class directly -- it will be automatically
293 used by DBIC where joins are needed.
295 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
296 Offline utilities may wish to use this class directly.
302 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.
305 =head2 Sanity-Check Reload of Development Server
307 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:
309 $ script/myapp_server.pl
311 Look for the three new model objects in the startup debug output:
314 .-------------------------------------------------------------------+----------.
316 +-------------------------------------------------------------------+----------+
317 | MyApp::Controller::Books | instance |
318 | MyApp::Controller::Root | instance |
319 | MyApp::Model::MyAppDB | instance |
320 | MyApp::Model::MyAppDB::Author | class |
321 | MyApp::Model::MyAppDB::Book | class |
322 | MyApp::Model::MyAppDB::BookAuthor | class |
323 | MyApp::Model::MyAppDB::Role | class |
324 | MyApp::Model::MyAppDB::User | class |
325 | MyApp::Model::MyAppDB::UserRole | class |
326 | MyApp::View::TT | instance |
327 '-------------------------------------------------------------------+----------'
330 Again, notice that your "result source" classes have been "re-loaded" by Catalyst under C<MyApp::Model>.
333 =head2 Include Authentication and Session Plugins
335 Edit C<lib/MyApp.pm> and update it as follows (everything below C<DefaultEnd> is new):
346 Authentication::Store::DBIC
347 Authentication::Credential::Password
350 Session::Store::FastMmap
351 Session::State::Cookie
354 The three C<Authentication> plugins work together to support
355 Authentication while the C<Session> plugins are required to maintain
356 state across multiple HTTP requests. Note that there are several
357 options for L<Session::Store|Catalyst::Plugin::Session::Store> (although
358 L<Session::Store::FastMmap|Catalyst::Plugin::Session::Store::FastMmap>
359 is generally a good choice if you are on Unix; try
360 L<Cache::FileCache|Catalyst::Plugin::Cache::FileCache> if you are on
361 Win32) -- consult L<Session::Store|Catalyst::Plugin::Session::Store> and
362 its subclasses for additional information.
364 =head2 Configure Authentication
366 Although C<__PACKAGE__-E<gt>config(name =E<gt> 'value');> is still
367 supported, newer Catalyst applications tend to place all configuration
368 information in C<myapp.yml> and automatically load this information into
369 C<MyApp-E<gt>config> using the
370 L<ConfigLoader|Catalyst::Plugin::ConfigLoader> plugin.
372 Edit the C<myapp.yml> YAML and update it to match:
378 # Note this first definition would be the same as setting
379 # __PACKAGE__->config->{authentication}->{dbic}->{user_class} = 'MyAppDB::User'
380 # in lib/MyApp.pm (IOW, each hash key becomes a "name:" in the YAML file).
382 # This is the model object created by Catalyst::Model::DBIC from your
383 # schema (you created 'MyAppDB::User' but as the Catalyst startup
384 # debug messages show, it was loaded as 'MyApp::Model::MyAppDB::User').
385 # NOTE: Omit 'MyAppDB::Model' to avoid a component lookup issue in Catalyst 5.66
386 user_class: MyAppDB::User
387 # This is the name of the field in your 'users' table that contains the user's name
389 # This is the name of the field in your 'users' table that contains the password
390 password_field: password
391 # Other options can go here for hashed passwords
393 Inline comments in the code above explain how each field is being used.
395 B<TIP>: Although YAML uses a very simple and easy-to-ready format, it
396 does require the use of a consistent level of indenting. Be sure you
397 line up everything on a given 'level' with the same number of indents.
398 Also, be sure not to use C<tab> characters (YAML does not support them
399 because they are handled inconsistently across editors).
401 =head2 Add Login and Logout Controllers
403 Use the Catalyst create script to create two stub controller files:
405 $ script/myapp_create.pl controller Login
406 $ script/myapp_create.pl controller Logout
408 B<NOTE>: You could easily use a single controller here. For example,
409 you could have a C<User> controller with both C<login> and C<logout>
410 actions. Remember, Catalyst is designed to be very flexible, and leaves
411 such matters up to you, the designer and programmer.
413 Then open C<lib/MyApp/Controller/Login.pm> and add:
421 sub default : Private {
424 # Get the username and password from form
425 my $username = $c->request->params->{username} || "";
426 my $password = $c->request->params->{password} || "";
428 # If the username and password values were found in form
429 if ($username && $password) {
430 # Attempt to log the user in
431 if ($c->login($username, $password)) {
432 # If successful, then let them use the application
433 $c->response->redirect($c->uri_for('/books/list'));
436 # Set an error message
437 $c->stash->{error_msg} = "Bad username or password.";
441 # If either of above don't work out, send to the login page
442 $c->stash->{template} = 'login.tt2';
445 This controller fetches the C<username> and C<password> values from the
446 login form and attempts to perform a login. If successful, it redirects
447 the user to the book list page. If the login fails, the user will stay
448 at the login page but receive an error message. If the C<username> and
449 C<password> values are not present in the form, the user will be taken
450 to the empty login form.
452 Next, create a corresponding method in C<lib/MyApp/Controller/Logout.pm>:
460 sub default : Private {
463 # Clear the user's state
466 # Send the user to the starting point
467 $c->response->redirect($c->uri_for('/'));
471 =head2 Add a Login Form TT Template Page
473 Create a login form by opening C<root/src/login.tt2> and inserting:
475 [% META title = 'Login' %]
478 <form method="post" action=" [% Catalyst.uri_for('/login') %] ">
482 <td><input type="text" name="username" size="40" /></td>
486 <td><input type="password" name="password" size="40" /></td>
489 <td colspan="2"><input type="submit" name="submit" value="Submit" /></td>
495 =head2 Add Valid User Check
497 We need something that provides enforcement for the authentication
498 mechanism -- a I<global> mechanism that prevents users who have not
499 passed authentication from reaching any pages except the login page.
500 This is generally done via an C<auto> action/method (prior to Catalyst
501 v5.66, this sort of thing would go in C<MyApp.pm>, but starting in
502 v5.66, the preferred location is C<lib/MyApp/Controller/Root.pm>).
504 Edit the existing C<lib/MyApp/Controller/Root.pm> class file and insert
505 the following method:
509 Check if there is a user and, if not, forward to login page
513 # Note that 'auto' runs after 'begin' but before your actions and that
514 # 'auto' "chain" (all from application path to most specific class are run)
518 # Allow unauthenticated users to reach the login page
519 if ($c->request->path =~ /login/) {
523 # If a user doesn't exist, force login
524 if (!$c->user_exists) {
525 # Dump a log message to the development server debug output
526 $c->log->debug('***Root::auto User not found, forwarding to /login');
527 # Redirect the user to the login page
528 $c->response->redirect($c->uri_for('/login'));
529 # Return 0 to cancel 'post-auto' processing and prevent use of application
533 # User found, so return 1 to continue with processing after this 'auto'
537 B<Note:> Catalyst provides a number of different types of actions, such
538 as C<Local>, C<Regex>, and C<Private>. You should refer to
539 L<Catalyst::Manual::Intro> for a more detailed explanation, but the
540 following bullet points provide a quick introduction:
546 The majority of application use C<Local> actions for items that respond
547 to user requests and C<Private> actions for those that do not directly
548 respond to user input.
552 There are five types of C<Private> actions: C<begin>, C<end>,
553 C<default>, C<index>, and C<auto>.
557 Unlike the other private C<Private> actions where only a single method
558 is called for each request, I<every> auto action along the chain of
559 namespaces will be called.
563 By placing the authentication enforcement code inside the C<auto> method
564 of C<lib/MyApp/Controller/Root.pm> (or C<lib/MyApp.pm>), it will be
565 called for I<every> request that is received by the entire application.
567 =head2 Displaying Content Only to Authenticated Users
569 Let's say you want to provide some information on the login page that
570 changes depending on whether the user has authenticated yet. To do
571 this, open C<root/src/login.tt2> in your editor and add the following
572 lines to the bottom of the file:
576 # This code illustrates how certain parts of the TT
577 # template will only be shown to users who have logged in
579 [% IF Catalyst.user %]
580 Please Note: You are already logged in as '[% Catalyst.user.username %]'.
581 You can <a href="[% Catalyst.uri_for('/logout') %]">logout</a> here.
583 You need to log in to use this application.
586 Note that this whole block is a comment because the "#" appears
587 immediate after the "[%" (with no spaces in between). Although it
588 can be a handy way to temporarily "comment out" a whole block of
589 TT code, it's probably a little too subtle for use in "normal"
593 Although most of the code is comments, the middle few lines provide a
594 "you are already logged in" reminder if the user returns to the login
595 page after they have already authenticated. For users who have not yet
596 authenticated, a "You need to log in..." message is displayed (note the
597 use of an IF-THEN-ELSE construct in TT).
600 =head2 Try Out Authentication
602 Press C<Ctrl-C> to kill the previous server instance (if it's still
603 running) and restart it:
605 $ script/myapp_server.pl
607 B<IMPORTANT NOTE>: If you happen to be using Internet Explorer, you may
608 need to use the command C<script/myapp_server.pl -k> to enable the
609 keepalive feature in the development server. Otherwise, the HTTP
610 redirect on successful login may not work correctly with IE (it seems to
611 work without -k if you are running the web browser and development
612 server on the same machine). If you are using browser a browser other
613 than IE, it should work either way. If you want to make keepalive the
614 default, you can edit C<script/myapp_server.pl> and change the
615 initialization value for C<$keepalive> to C<1>. (You will need to do
616 this every time you create a new Catalyst application or rebuild the
617 C<myapp_server.pl> script.)
619 Now trying going to L<http://localhost:3000/books/list> and you should
620 be redirected to the login page, hitting Shift+Reload if necessary (the
621 "You are already logged in" message should I<not> appear -- if it does,
622 click the C<logout> button and try again). Note the C<***Root::auto User
623 not found...> debug message in the development server output. Enter
624 username C<test01> and password C<mypass>, and you should be taken to
627 Open C<root/src/books/list.tt2> and add the following lines to the
631 <a href="[% Catalyst.uri_for('/login') %]">Login</a>
632 <a href="[% Catalyst.uri_for('form_create') %]">Create</a>
635 Reload your browser and you should now see a "Login" link at the bottom
636 of the page (as mentioned earlier, you can update template files without
637 reloading the development server). Click this link to return to the
638 login page. This time you I<should> see the "You are already logged in"
641 Finally, click the C<You can logout here> link on the C</login> page.
642 You should stay at the login page, but the message should change to "You
643 need to log in to use this application."
646 =head1 USING PASSWORD HASHES
648 In this section we increase the security of our system by converting
649 from cleartext passwords to SHA-1 password hashes.
651 B<Note:> This section is optional. You can skip it and the rest of the
652 tutorial will function normally.
654 Note that even with the techniques shown in this section, the browser
655 still transmits the passwords in cleartext to your application. We are
656 just avoiding the I<storage> of cleartext passwords in the database by
657 using a SHA-1 hash. If you are concerned about cleartext passwords
658 between the browser and your application, consider using SSL/TLS, made
659 easy with the Catalyst plugin L<Catalyst::Plugin:RequireSSL>.
661 =head2 Get a SHA-1 Hash for the Password
663 Catalyst uses the C<Digest> module to support a variety of hashing
664 algorithms. Here we will use SHA-1 (SHA = Secure Hash Algorithm).
665 First, we should compute the SHA-1 hash for the "mypass" password we are
666 using. The following command-line Perl script provides a "quick and
667 dirty" way to do this:
669 $ perl -MDigest::SHA -e 'print Digest::SHA::sha1_hex("mypass"), "\n"'
670 e727d1464ae12436e899a726da5b2f11d8381b26
673 =head2 Switch to SHA-1 Password Hashes in the Database
675 Next, we need to change the C<password> column of our C<users> table to
676 store this hash value vs. the existing cleartext password. Open
677 C<myapp03.sql> in your editor and enter:
680 -- Convert passwords to SHA-1 hashes
682 UPDATE users SET password = 'e727d1464ae12436e899a726da5b2f11d8381b26' WHERE id = 1;
683 UPDATE users SET password = 'e727d1464ae12436e899a726da5b2f11d8381b26' WHERE id = 2;
684 UPDATE users SET password = 'e727d1464ae12436e899a726da5b2f11d8381b26' WHERE id = 3;
686 Then use the following command to update the SQLite database:
688 $ sqlite3 myapp.db < myapp03.sql
690 B<Note:> We are using SHA-1 hashes here, but many other hashing
691 algorithms are supported. See C<Digest> for more information.
693 =head2 Enable SHA-1 Hash Passwords in
694 C<Catalyst::Plugin::Authentication::Store::DBIC>
696 Edit C<myapp.yml> and update it to match (the C<password_type> and
697 C<password_hash_type> are new, everything else is the same):
703 # Note this first definition would be the same as setting
704 # __PACKAGE__->config->{authentication}->{dbic}->{user_class} = 'MyAppDB::User'
705 # in lib/MyApp.pm (IOW, each hash key becomes a "name:" in the YAML file).
707 # This is the model object created by Catalyst::Model::DBIC from your
708 # schema (you created 'MyAppDB::User' but as the Catalyst startup
709 # debug messages show, it was loaded as 'MyApp::Model::MyAppDB::User').
710 # NOTE: Omit 'MyAppDB::Model' to avoid a component lookup issue in Catalyst 5.66
711 user_class: MyAppDB::User
712 # This is the name of the field in your 'users' table that contains the user's name
714 # This is the name of the field in your 'users' table that contains the password
715 password_field: password
716 # Other options can go here for hashed passwords
717 # Enabled hashed passwords
718 password_type: hashed
719 # Use the SHA-1 hashing algorithm
720 password_hash_type: SHA-1
723 =head2 Try Out the Hashed Passwords
725 Press C<Ctrl-C> to kill the previous server instance (if it's still
726 running) and restart it:
728 $ script/myapp_server.pl
730 You should now be able to go to L<http://localhost:3000/books/list> and
731 login as before. When done, click the "Logout" link on the login page
732 (or point your browser at L<http://localhost:3000/logout>).
736 Kennedy Clark, C<hkclark@gmail.com>
738 Please report any errors, issues or suggestions to the author.
740 Copyright 2006, Kennedy Clark. All rights reserved.
742 This library is free software; you can redistribute it and/or modify it
743 under the same terms as Perl itself.