3 Catalyst::Manual::Tutorial::Authentication - Catalyst Tutorial Part 4: Authentication
9 This is B<Part 4 of 9> for the Catalyst tutorial.
11 L<Totorial Overview|Catalyst::Manual::Tutorial>
17 L<Introduction|Catalyst::Manual::Tutorial::Intro>
21 L<Catalyst Basics|Catalyst::Manual::Tutorial::CatalystBasics>
25 L<Basic CRUD|Catalyst::Manual::Tutorial03_BasicCRUD>
33 L<Authorization|Catalyst::Manual::Tutorial::Authorization>
37 L<Debugging|Catalyst::Manual::Tutorial::Debugging>
41 L<Testing|Catalyst::Manual::Tutorial::Testing>
45 L<AdvancedCRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
49 L<Appendicies|Catalyst::Manual::Tutorial::Appendicies>
57 Now that we finally have a simple yet functional application, we can focus on providing authentication (with authorization coming in Part 5).
59 This part of the tutorial is divided into two main sections: 1) basic, cleartext authentication and 2) hash-based authentication.
61 B<TIP>: Note that all of the code for this part of the tutorial can be pulled from the Catalyst Subversion repository in one step with the following command:
63 svn checkout http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/Tutorial@###
64 IMPORTANT: Does not work yet. Will be completed for final version.
68 =head1 BASIC AUTHENTICATION
70 This section explores how add authentication logic to a Catalyst application.
73 =head2 Add Users and Roles to the Database
75 First, we add both user and role information to the database (we add the role information here although it will not be used until the authorization section, Part 5). Create a new SQL script file by opening C<myapp02.sql> in your editor and insert:
78 -- Add users and roles tables, along with a many-to-many join table
81 id INTEGER PRIMARY KEY,
90 id INTEGER PRIMARY KEY,
93 CREATE TABLE user_roles (
96 PRIMARY KEY (user_id, role_id)
99 -- Load up some initial test data
101 INSERT INTO users VALUES (1, 'test01', 'mypass', 't01@na.com', 'Joe', 'Blow', 1);
102 INSERT INTO users VALUES (2, 'test02', 'mypass', 't02@na.com', 'Jane', 'Doe', 1);
103 INSERT INTO users VALUES (3, 'test03', 'mypass', 't03@na.com', 'No', 'Go', 0);
104 INSERT INTO roles VALUES (1, 'user');
105 INSERT INTO roles VALUES (2, 'admin');
106 INSERT INTO user_roles VALUES (1, 1);
107 INSERT INTO user_roles VALUES (1, 2);
108 INSERT INTO user_roles VALUES (2, 1);
109 INSERT INTO user_roles VALUES (3, 1);
111 Then load this into the C<myapp.db> database with the following command:
113 $ sqlite3 myapp.db < myapp02.sql
116 =head2 Add User and Role Information to Dbic Schema
118 This step adds DBIC-based classes for the user-related database tables (the role information will not be used until the Part 5):
120 Edit C<lib/MyAppDB.pm> and update the contents to match (only the C<MyAppDB =E<gt> [qw/Book BookAuthor Author User UserRole Role/]> line has changed):
126 MyAppDB -- DBIC Schema Class
130 # Our schema needs to inherit from 'DBIx::Class::Schema'
131 use base qw/DBIx::Class::Schema/;
133 # Need to load the DB Model classes here.
134 # You can use this syntax if you want:
135 # __PACKAGE__->load_classes(qw/Book BookAuthor Author User UserRole Role/);
136 # Also, if you simply want to load all of the classes in a directory
137 # of the same name as your schema class (as we do here) you can use:
138 # __PACKAGE__->load_classes(qw//);
139 # But the variation below is more flexible in that it can be used to
140 # load from multiple namespaces.
141 __PACKAGE__->load_classes({
142 MyAppDB => [qw/Book BookAuthor Author User UserRole Role/]
148 =head2 Create New "Result Source Objects"
150 Create the following three files with the content shown below.
152 C<lib/MyAppDB/User.pm>:
154 package MyAppDB::User;
156 use base qw/DBIx::Class/;
158 # Load required DBIC stuff
159 __PACKAGE__->load_components(qw/PK::Auto Core/);
161 __PACKAGE__->table('users');
162 # Set columns in table
163 __PACKAGE__->add_columns(qw/id username password email_address first_name last_name/);
164 # Set the primary key for the table
165 __PACKAGE__->set_primary_key('id');
173 # 1) Name of relationship, DBIC will create accessor with this name
174 # 2) Name of the model class referenced by this relationship
175 # 3) Column name in *foreign* table
176 __PACKAGE__->has_many(map_user_role => 'MyAppDB::UserRole', 'user_id');
181 MyAppDB::User - A model object representing a person with access to the system.
185 This is an object that represents a row in the 'users' table of your application
186 database. It uses DBIx::Class (aka, DBIC) to do ORM.
188 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
189 Offline utilities may wish to use this class directly.
196 C<lib/MyAppDB/Role.pm>:
198 package MyAppDB::Role;
200 use base qw/DBIx::Class/;
202 # Load required DBIC stuff
203 __PACKAGE__->load_components(qw/PK::Auto Core/);
205 __PACKAGE__->table('roles');
206 # Set columns in table
207 __PACKAGE__->add_columns(qw/id role/);
208 # Set the primary key for the table
209 __PACKAGE__->set_primary_key('id');
217 # 1) Name of relationship, DBIC will create accessor with this name
218 # 2) Name of the model class referenced by this relationship
219 # 3) Column name in *foreign* table
220 __PACKAGE__->has_many(map_user_role => 'MyAppDB::UserRole', 'role_id');
225 MyAppDB::Role - A model object representing a class of access permissions to
230 This is an object that represents a row in the 'roles' table of your
231 application database. It uses DBIx::Class (aka, DBIC) to do ORM.
233 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
234 "Offline" utilities may wish to use this class directly.
241 C<lib/MyAppDB/UserRole.pm>:
243 package MyAppDB::UserRole;
245 use base qw/DBIx::Class/;
247 # Load required DBIC stuff
248 __PACKAGE__->load_components(qw/PK::Auto Core/);
250 __PACKAGE__->table('user_roles');
251 # Set columns in table
252 __PACKAGE__->add_columns(qw/user_id role_id/);
253 # Set the primary key for the table
254 __PACKAGE__->set_primary_key(qw/user_id role_id/);
262 # 1) Name of relationship, DBIC will create accessor with this name
263 # 2) Name of the model class referenced by this relationship
264 # 3) Column name in *this* table
265 __PACKAGE__->belongs_to(user => 'MyAppDB::User', 'user_id');
269 # 1) Name of relationship, DBIC will create accessor with this name
270 # 2) Name of the model class referenced by this relationship
271 # 3) Column name in *this* table
272 __PACKAGE__->belongs_to(role => 'MyAppDB::Role', 'role_id');
277 MyAppDB::UserRole - A model object representing the JOIN between Users and Roles.
281 This is an object that represents a row in the 'user_roles' table of your application
282 database. It uses DBIx::Class (aka, DBIC) to do ORM.
284 You probably won't need to use this class directly -- it will be automatically
285 used by DBIC where joins are needed.
287 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
288 Offline utilities may wish to use this class directly.
294 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.
297 =head2 Sanity-Check Reload of Development Server
299 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:
301 $ script/myapp_server.pl
303 Look for the three new model objects in the startup debug output:
306 .-------------------------------------------------------------------+----------.
308 +-------------------------------------------------------------------+----------+
309 | MyApp::Controller::Books | instance |
310 | MyApp::Controller::Root | instance |
311 | MyApp::Model::MyAppDB | instance |
312 | MyApp::Model::MyAppDB::Author | class |
313 | MyApp::Model::MyAppDB::Book | class |
314 | MyApp::Model::MyAppDB::BookAuthor | class |
315 | MyApp::Model::MyAppDB::Role | class |
316 | MyApp::Model::MyAppDB::User | class |
317 | MyApp::Model::MyAppDB::UserRole | class |
318 | MyApp::View::TT | instance |
319 '-------------------------------------------------------------------+----------'
322 Again, notice that your "result source" classes have been "re-loaded" by Catalyst under C<MyApp::Model>.
325 =head2 Include Authentication and Session Plugins
327 Edit C<lib/MyApp.pm> and update it as follows (everything below C<DefaultEnd> is new):
339 Authentication::Store::DBIC
340 Authentication::Credential::Password
343 Session::Store::FastMmap
344 Session::State::Cookie
347 The three C<Authentication> plugins work together to support Authentication while the C<Session> plugins are required to maintain state across multiple HTTP requests. Note that there are several options for L<Session::Store|Catalyst::Plugin::Session::Store> (although L<Session::Store::FastMmap|Catalyst::Plugin::Session::Store::FastMmap> is generally a good choice if you are on Unix; try L<Cache::FileCache|Catalyst::Plugin::Cache::FileCache> if you are on Win32) -- consult L<Session::Store|Catalyst::Plugin::Session::Store> and its subclasses for additional information.
350 =head2 Configure Authentication
352 Although C<__PACKAGE__-E<gt>config(name =E<gt> 'value');> is still supported, newer Catalyst applications tend to place all configuration information in C<myapp.yml> and automatically load this information into C<MyApp-E<gt>config> using the L<ConfigLoader|Catalyst::Plugin::ConfigLoader> plugin.
354 Edit the C<myapp.yml> YAML and update it to match:
360 # Note this first definition would be the same as setting
361 # __PACKAGE__->config->{authentication}->{dbic}->{user_class} = 'MyAppDB::User'
362 # in lib/MyApp.pm (IOW, each hash key becomes a "name:" in the YAML file).
364 # This is the model object created by Catalyst::Model::DBIC from your
365 # schema (you created 'MyAppDB::User' but as the Catalyst startup
366 # debug messages show, it was loaded as 'MyApp::Model::MyAppDB::User').
367 # NOTE: Omit 'MyAppDB::Model' to avoid a component lookup issue in Catalyst 5.66
368 user_class: MyAppDB::User
369 # This is the name of the field in your 'users' table that contains the user's name
371 # This is the name of the field in your 'users' table that contains the password
372 password_field: password
373 # Other options can go here for hashed passwords
375 Inline comments in the code above explain how each field is being used.
377 B<TIP>: Although YAML uses a very simple and easy-to-ready format, it does require the use of a consistent level of indenting. Be sure you line up everything on a given 'level' with the same number of indents. Also, be sure not to use C<tab> characters (YAML does not support them because they are handled inconsistently across editors).
380 =head2 Add Login and Logout Controllers
382 Use the Catalyst create script to create two stub controller files:
384 $ script/myapp_create.pl controller Login
385 $ script/myapp_create.pl controller Logout
387 B<NOTE>: You could easily use a single controller here. For example, you could have a C<User> controller with both C<login> and C<logout> actions. Remember, Catalyst is designed to be very flexible, and leaves such matters up to you, the designer and programmer.
389 Then open C<lib/MyApp/Controller/Login.pm> and add:
397 sub default : Private {
400 # Get the username and password from form
401 my $username = $c->request->params->{username} || "";
402 my $password = $c->request->params->{password} || "";
404 # If the username and password values were found in form
405 if ($username && $password) {
406 # Attempt to log the user in
407 if ($c->login($username, $password)) {
408 # If successful, then let them use the application
409 $c->response->redirect($c->uri_for('/books/list'));
412 # Set an error message
413 $c->stash->{error_msg} = "Bad username or password.";
417 # If either of above don't work out, send to the login page
418 $c->stash->{template} = 'login.tt2';
421 This controller fetches the C<username> and C<password> values from the login form and attempts to perform a login. If successful, it redirects the user to the book list page. If the login fails, the user will stay at the login page but receive an error message. If the C<username> and C<password> values are not present in the form, the user will be taken to the empty login form.
423 Next, create a corresponding method in C<lib/MyApp/Controller/Logout.pm>:
431 sub default : Private {
434 # Clear the user's state
437 # Send the user to the starting
438 $c->response->redirect($c->uri_for('/'));
442 =head2 Add a Login Form TT Template Page
444 Create a login form by opening C<root/src/login.tt2> and inserting:
446 [% META title = 'Login' %]
449 <form method="post" action=" [% Catalyst.uri_for('/login') %] ">
453 <td><input type="text" name="username" size="40" /></td>
457 <td><input type="password" name="password" size="40" /></td>
460 <td colspan="2"><input type="submit" name="submit" value="Submit" /></td>
466 =head2 Add Valid User Check
468 We need something that provides enforcement for the authentication mechanism -- a I<global> mechanism that prevents users who have not passed authentication from reaching any pages except the login page. This is generally done via an C<auto> action/method (prior to Catalyst v5.66, this sort of thing would go in C<MyApp.pm>, but starting in v5.66, the preferred location is C<lib/MyApp/Controller/Root.pm>).
470 Edit the existing C<lib/MyApp/Controller/Root.pm> class file and insert the following method:
474 Check if there is a user and, if not, forward to login page
478 # Note that 'auto' runs after 'begin' but before your actions and that
479 # 'auto' "chain" (all from application path to most specific class are run)
483 # Allow unauthenticated users to reach the login page
484 if ($c->request->path =~ /login/) {
488 # If a user doesn't exist, force login
489 if (!$c->user_exists) {
490 # Dump a log message to the development server debug output
491 $c->log->debug('***Root::auto User not found, forwarding to /login');
492 # Redirect the user to the login page
493 $c->response->redirect($c->uri_for('/login'));
494 # Return 0 to cancel 'post-auto' processing and prevent use of application
498 # User found, so return 1 to continue with processing after this 'auto'
502 B<Note:> Catalyst provides a number of different types of actions, such as C<Local>, C<Regex>, and C<Private>. You should refer to L<Catalyst::Manual::Intro|Catalyst::Manual::Intro> for a more detailed explanation, but the following bullet points provide a quick introduction:
508 The majority of application use C<Local> actions for items that respond to user requests and C<Private> actions for those that do not directly respond to user input.
512 There are five types of C<Private> actions: C<begin>, C<end>, C<default>, C<index>, and C<auto>.
516 Unlike the other private C<Private> actions where only a single method is called for each request, I<every> auto action along the chain of namespaces will be called.
520 By placing the authentication enforcement code inside the C<auto> method of C<lib/MyApp/Controller/Root.pm> (or C<lib/MyApp.pm>), it will be called for I<every> request that is received by the entire application.
523 =head2 Displaying Content Only to Authenticated Users
525 Let's say you want to provide some information on the login page that changes depending on whether the user has authenticated yet. To do this, open C<root/src/login.tt2> in your editor and add the following lines to the bottom of the file:
529 # This code illustrates how certain parts of the TT
530 # template will only be shown to users who have logged in
532 [% IF Catalyst.user %]
533 Please Note: You are already logged in as '[% Catalyst.user.username %]'.
534 You can <a href="[% Catalyst.uri_for('/logout') %]">logout</a> here.
536 You need to log in to use this application.
539 Note that this whole block is a comment because the "#" appears
540 immediate after the "[%" (with no spaces in between). Although it
541 can be a handy way to temporarily "comment out" a whole block of
542 TT code, it's probably a little too subtle for use in "normal"
546 Although most of the code is comments, the middle few lines provide a "you are already logged in" reminder if the user returns to the login page after they have already authenticated. For users who have not yet authenticated, a "You need to log in..." message is displayed (note the use of an IF-THEN-ELSE construct in TT).
549 =head2 Try Out Authentication
551 Press C<Ctrl-C> to kill the previous server instance (if it's still running) and
554 $ script/myapp_server.pl
556 B<IMPORTANT NOTE>: If you happen to be using Internet Explorer, you may need to use the command C<script/myapp_server.pl -k> to enable the keepalive feature in the development server. Otherwise, the HTTP redirect on successful login may not work correctly with IE (it seems to work without k if you are running the web browser and development server on the same machine). If you are using browser a browser other than IE, it should work either way. If you want to make keepalive the default, you can edit C<script/myapp_server.pl> and change the initialization value for C<$keepalive> to C<1>. (You will need to do this every time you create a new Catalyst application or rebuild the C<myapp_server.pl> script.)
558 Now trying going to L<http://localhost:3000/books/list> and you should be redirected to the login page, hitting Shift+Reload if necessary (the "You are already logged in" message should I<not> appear -- if it does, click the C<logout> button and try again). Make note of the C<***Root::auto User not found...> debug message in the development server output. Enter username C<test01> and password C<mypass>, and you should be taken to the Book List page.
560 Open C< root/src/books/list.tt2> and add the following lines to the bottom:
563 <a href="[% Catalyst.uri_for('/login') %]">Login</a>
564 <a href="[% Catalyst.uri_for('form_create') %]">Create</a>
567 Reload your browser and you should now see a "Login" link at the bottom of the page (as mentioned earlier, you can update template files without reloading the development server). Click this link to return to the login page. This time you I<should> see the "You are already logged in" message.
569 Finally, click the C<You can logout here> link on the C</login> page. You should stay at the login page, but the message should change to "You need to log in to use this application."
573 =head1 USING PASSWORD HASHES
575 In this section we increase the security of our system by converting from cleartext passwords to SHA-1 password hashes.
577 B<Note:> This section is optional. You can skip it and the rest of the tutorial will function normally.
579 Note that even with the techniques shown in this section, the browser still transmits the passwords in cleartext to your application. We are just avoiding the I<storage> of cleartext passwords in the database by using a SHA-1 hash. If you are concerned about cleartext passwords between the browser and your application, consider using SSL/TLS.
582 =head2 Get a SHA-1 Hash for the Password
584 Catalyst uses the C<Digest > module to support a variety of hashing algorithms. Here we will use SHA-1 (SHA = Secure Hash Algorithm). First, we should compute the SHA-1 hash for the "mypass" password we are using. The following command-line Perl script provides a "quick and dirty" way to do this:
586 $ perl -MDigest::SHA -e 'print Digest::SHA::sha1_hex("mypass"), "\n"'
587 e727d1464ae12436e899a726da5b2f11d8381b26
591 =head2 Switch to SHA-1 Password Hashes in the Database
593 Next, we need to change the C<password> column of our C<users> table to store this hash value vs. the existing cleartext password. Open C<myapp03.sql> in your editor and enter:
596 -- Convert passwords to SHA-1 hashes
598 UPDATE users SET password = 'e727d1464ae12436e899a726da5b2f11d8381b26' WHERE id = 1;
599 UPDATE users SET password = 'e727d1464ae12436e899a726da5b2f11d8381b26' WHERE id = 2;
600 UPDATE users SET password = 'e727d1464ae12436e899a726da5b2f11d8381b26' WHERE id = 3;
602 Then use the following command to update the SQLite database:
604 $ sqlite3 myapp.db < myapp03.sql
606 B<Note:> We are using SHA-1 hashes here, but many other hashing algorithms are supported. See C<Digest > for more information.
609 =head2 Enable SHA-1 Hash Passwords in C<Catalyst::Plugin::Authentication::Store::DBIC>
611 Edit C<myapp.yml> and update it to match (the C<password_type> and C<password_hash_type> are new, everything else is the same):
617 # Note this first definition would be the same as setting
618 # __PACKAGE__->config->{authentication}->{dbic}->{user_class} = 'MyAppDB::User'
619 # in lib/MyApp.pm (IOW, each hash key becomes a "name:" in the YAML file).
621 # This is the model object created by Catalyst::Model::DBIC from your
622 # schema (you created 'MyAppDB::User' but as the Catalyst startup
623 # debug messages show, it was loaded as 'MyApp::Model::MyAppDB::User').
624 # NOTE: Omit 'MyAppDB::Model' to avoid a component lookup issue in Catalyst 5.66
625 user_class: MyAppDB::User
626 # This is the name of the field in your 'users' table that contains the user's name
628 # This is the name of the field in your 'users' table that contains the password
629 password_field: password
630 # Other options can go here for hashed passwords
631 # Enabled hashed passwords
632 password_type: hashed
633 # Use the SHA-1 hashing algorithm
634 password_hash_type: SHA-1
637 =head2 Try Out the Hashed Passwords
639 Press C<Ctrl-C> to kill the previous server instance (if it's still running) and restart it:
641 $ script/myapp_server.pl
643 You should now be able to go to L<http://localhost:3000/books/list> and login as before. When done, click the "Logout" link on the login page (or point your browser at L<http://localhost:3000/logout>).
649 Kennedy Clark, C<hkclark@gmail.com>
651 Please report any errors, issues or suggestions to the author.
653 Copyright 2006, Kennedy Clark. All rights reserved.
655 This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.