Update logic in Root.pm allowing unauth access to the Login controller.
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Manual / Tutorial / Authentication.pod
CommitLineData
4d583dd8 1=head1 NAME
2
64ccd8a8 3Catalyst::Manual::Tutorial::Authentication - Catalyst Tutorial - Part 4: Authentication
4d583dd8 4
5
4d583dd8 6=head1 OVERVIEW
7
8This is B<Part 4 of 9> for the Catalyst tutorial.
9
64ccd8a8 10L<Tutorial Overview|Catalyst::Manual::Tutorial>
4d583dd8 11
12=over 4
13
14=item 1
15
16L<Introduction|Catalyst::Manual::Tutorial::Intro>
17
18=item 2
19
20L<Catalyst Basics|Catalyst::Manual::Tutorial::CatalystBasics>
21
22=item 3
23
64ccd8a8 24L<Basic CRUD|Catalyst::Manual::Tutorial_BasicCRUD>
4d583dd8 25
26=item 4
27
28B<Authentication>
29
30=item 5
31
32L<Authorization|Catalyst::Manual::Tutorial::Authorization>
33
34=item 6
35
36L<Debugging|Catalyst::Manual::Tutorial::Debugging>
37
38=item 7
39
40L<Testing|Catalyst::Manual::Tutorial::Testing>
41
42=item 8
43
44L<AdvancedCRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
45
46=item 9
47
7d310f12 48L<Appendices|Catalyst::Manual::Tutorial::Appendices>
4d583dd8 49
50=back
51
52
4d583dd8 53=head1 DESCRIPTION
54
64ccd8a8 55Now that we finally have a simple yet functional application, we can
71dedf57 56focus on providing authentication (with authorization coming next in
57Part 5).
4d583dd8 58
64ccd8a8 59This part of the tutorial is divided into two main sections: 1) basic,
60cleartext authentication and 2) hash-based authentication.
4d583dd8 61
64ccd8a8 62B<TIP>: Note that all of the code for this part of the tutorial can be
63pulled from the Catalyst Subversion repository in one step with the
64following command:
4d583dd8 65
7d310f12 66 svn co http://dev.catalyst.perl.org/repos/Catalyst/tags/examples/Tutorial/MyApp/5.7/Authentication MyApp
4d583dd8 67
68
4d583dd8 69=head1 BASIC AUTHENTICATION
70
71dedf57 71This section explores how to add authentication logic to a Catalyst
72application.
4d583dd8 73
a63e6e67 74
4d583dd8 75=head2 Add Users and Roles to the Database
76
71dedf57 77First, we add both user and role information to the database (we will
78add the role information here although it will not be used until the
64ccd8a8 79authorization section, Part 5). Create a new SQL script file by opening
80C<myapp02.sql> in your editor and insert:
4d583dd8 81
82 --
83 -- Add users and roles tables, along with a many-to-many join table
84 --
85 CREATE TABLE users (
86 id INTEGER PRIMARY KEY,
87 username TEXT,
88 password TEXT,
89 email_address TEXT,
90 first_name TEXT,
91 last_name TEXT,
92 active INTEGER
93 );
94 CREATE TABLE roles (
95 id INTEGER PRIMARY KEY,
96 role TEXT
97 );
98 CREATE TABLE user_roles (
99 user_id INTEGER,
100 role_id INTEGER,
101 PRIMARY KEY (user_id, role_id)
102 );
103 --
104 -- Load up some initial test data
105 --
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);
115
116Then load this into the C<myapp.db> database with the following command:
117
118 $ sqlite3 myapp.db < myapp02.sql
119
120
71dedf57 121=head2 Add User and Role Information to DBIC Schema
4d583dd8 122
64ccd8a8 123This step adds DBIC-based classes for the user-related database tables
71dedf57 124(the role information will not be used until Part 5):
4d583dd8 125
64ccd8a8 126Edit C<lib/MyAppDB.pm> and update the contents to match (only the
127C<MyAppDB =E<gt> [qw/Book BookAuthor Author User UserRole Role/]> line
128has changed):
4d583dd8 129
130 package MyAppDB;
131
132 =head1 NAME
133
134 MyAppDB -- DBIC Schema Class
135
136 =cut
137
138 # Our schema needs to inherit from 'DBIx::Class::Schema'
139 use base qw/DBIx::Class::Schema/;
140
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/]
151 });
152
153 1;
154
155
156=head2 Create New "Result Source Objects"
157
158Create the following three files with the content shown below.
159
160C<lib/MyAppDB/User.pm>:
161
162 package MyAppDB::User;
163
164 use base qw/DBIx::Class/;
165
166 # Load required DBIC stuff
167 __PACKAGE__->load_components(qw/PK::Auto Core/);
168 # Set the table name
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');
174
175 #
176 # Set relationships:
177 #
178
179 # has_many():
180 # args:
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');
185
186
187 =head1 NAME
188
189 MyAppDB::User - A model object representing a person with access to the system.
190
191 =head1 DESCRIPTION
192
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.
195
196 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
197 Offline utilities may wish to use this class directly.
198
199 =cut
200
201 1;
202
203
204C<lib/MyAppDB/Role.pm>:
205
206 package MyAppDB::Role;
207
208 use base qw/DBIx::Class/;
209
210 # Load required DBIC stuff
211 __PACKAGE__->load_components(qw/PK::Auto Core/);
212 # Set the table name
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');
218
219 #
220 # Set relationships:
221 #
222
223 # has_many():
224 # args:
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');
229
230
231 =head1 NAME
232
233 MyAppDB::Role - A model object representing a class of access permissions to
234 the system.
235
236 =head1 DESCRIPTION
237
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.
240
241 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
242 "Offline" utilities may wish to use this class directly.
243
244 =cut
245
246 1;
247
248
249C<lib/MyAppDB/UserRole.pm>:
250
251 package MyAppDB::UserRole;
252
253 use base qw/DBIx::Class/;
254
255 # Load required DBIC stuff
256 __PACKAGE__->load_components(qw/PK::Auto Core/);
257 # Set the table name
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/);
263
264 #
265 # Set relationships:
266 #
267
268 # belongs_to():
269 # args:
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');
274
275 # belongs_to():
276 # args:
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');
281
282
283 =head1 NAME
284
285 MyAppDB::UserRole - A model object representing the JOIN between Users and Roles.
286
287 =head1 DESCRIPTION
288
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.
291
292 You probably won't need to use this class directly -- it will be automatically
293 used by DBIC where joins are needed.
294
295 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
296 Offline utilities may wish to use this class directly.
297
298 =cut
299
300 1;
301
302The 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.
303
304
305=head2 Sanity-Check Reload of Development Server
306
307We 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:
308
309 $ script/myapp_server.pl
310
311Look for the three new model objects in the startup debug output:
312
313 ...
314 .-------------------------------------------------------------------+----------.
315 | Class | Type |
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 '-------------------------------------------------------------------+----------'
328 ...
329
330Again, notice that your "result source" classes have been "re-loaded" by Catalyst under C<MyApp::Model>.
331
332
333=head2 Include Authentication and Session Plugins
334
33aee7ed 335Edit C<lib/MyApp.pm> and update it as follows (everything below C<StackTrace> is new):
4d583dd8 336
337 use Catalyst qw/
338 -Debug
339 ConfigLoader
340 Static::Simple
341
4d583dd8 342 StackTrace
4d583dd8 343
344 Authentication
345 Authentication::Store::DBIC
346 Authentication::Credential::Password
347
348 Session
349 Session::Store::FastMmap
350 Session::State::Cookie
351 /;
352
64ccd8a8 353The three C<Authentication> plugins work together to support
354Authentication while the C<Session> plugins are required to maintain
355state across multiple HTTP requests. Note that there are several
a63e6e67 356options for L<Session::Store|Catalyst::Plugin::Session::Store>
357(L<Session::Store::FastMmap|Catalyst::Plugin::Session::Store::FastMmap>
64ccd8a8 358is generally a good choice if you are on Unix; try
359L<Cache::FileCache|Catalyst::Plugin::Cache::FileCache> if you are on
360Win32) -- consult L<Session::Store|Catalyst::Plugin::Session::Store> and
361its subclasses for additional information.
4d583dd8 362
a63e6e67 363
4d583dd8 364=head2 Configure Authentication
365
64ccd8a8 366Although C<__PACKAGE__-E<gt>config(name =E<gt> 'value');> is still
367supported, newer Catalyst applications tend to place all configuration
368information in C<myapp.yml> and automatically load this information into
a63e6e67 369C<MyApp-E<gt>config> using the
370L<ConfigLoader|Catalyst::Plugin::ConfigLoader> plugin. Here, we need
371to load several parameters that tell
372L<Catalyst::Plugin::Authentication|Catalyst::Plugin::Authentication>
373where to locate information in your database. To do this, edit the
374C<myapp.yml> YAML and update it to match:
4d583dd8 375
376 ---
377 name: MyApp
378 authentication:
379 dbic:
380 # Note this first definition would be the same as setting
381 # __PACKAGE__->config->{authentication}->{dbic}->{user_class} = 'MyAppDB::User'
382 # in lib/MyApp.pm (IOW, each hash key becomes a "name:" in the YAML file).
383 #
384 # This is the model object created by Catalyst::Model::DBIC from your
385 # schema (you created 'MyAppDB::User' but as the Catalyst startup
386 # debug messages show, it was loaded as 'MyApp::Model::MyAppDB::User').
a63e6e67 387 # NOTE: Omit 'MyApp::Model' to avoid a component lookup issue in Catalyst 5.66
4d583dd8 388 user_class: MyAppDB::User
389 # This is the name of the field in your 'users' table that contains the user's name
390 user_field: username
391 # This is the name of the field in your 'users' table that contains the password
392 password_field: password
393 # Other options can go here for hashed passwords
394
395Inline comments in the code above explain how each field is being used.
396
64ccd8a8 397B<TIP>: Although YAML uses a very simple and easy-to-ready format, it
398does require the use of a consistent level of indenting. Be sure you
399line up everything on a given 'level' with the same number of indents.
400Also, be sure not to use C<tab> characters (YAML does not support them
401because they are handled inconsistently across editors).
4d583dd8 402
a63e6e67 403
4d583dd8 404=head2 Add Login and Logout Controllers
405
406Use the Catalyst create script to create two stub controller files:
407
408 $ script/myapp_create.pl controller Login
409 $ script/myapp_create.pl controller Logout
410
64ccd8a8 411B<NOTE>: You could easily use a single controller here. For example,
412you could have a C<User> controller with both C<login> and C<logout>
413actions. Remember, Catalyst is designed to be very flexible, and leaves
414such matters up to you, the designer and programmer.
4d583dd8 415
be16bacd 416Then open C<lib/MyApp/Controller/Login.pm>, locate the C<sub index :
417Private> method (this was automatically inserted by the helpers when we
418created the Login controller above), and delete this line:
419
420 $c->response->body('Matched MyApp::Controller::Login in Login.');
421
422Then update it to match:
4d583dd8 423
7d310f12 424 =head2 index
4d583dd8 425
426 Login logic
427
428 =cut
429
be16bacd 430 sub index : Private {
4d583dd8 431 my ($self, $c) = @_;
432
433 # Get the username and password from form
434 my $username = $c->request->params->{username} || "";
435 my $password = $c->request->params->{password} || "";
436
437 # If the username and password values were found in form
438 if ($username && $password) {
439 # Attempt to log the user in
440 if ($c->login($username, $password)) {
441 # If successful, then let them use the application
442 $c->response->redirect($c->uri_for('/books/list'));
443 return;
444 } else {
445 # Set an error message
446 $c->stash->{error_msg} = "Bad username or password.";
447 }
448 }
449
450 # If either of above don't work out, send to the login page
451 $c->stash->{template} = 'login.tt2';
452 }
453
64ccd8a8 454This controller fetches the C<username> and C<password> values from the
455login form and attempts to perform a login. If successful, it redirects
456the user to the book list page. If the login fails, the user will stay
457at the login page but receive an error message. If the C<username> and
458C<password> values are not present in the form, the user will be taken
459to the empty login form.
4d583dd8 460
7e5eb02c 461Note that we could have used something like C<sub default :Private>;
462however, the use of C<default> actions is discouraged because it does
463not receive path args as with other actions. The recommended practice
464is to only use C<default> in C<MyApp::Controller::Root>.
465
8112f931 466Another option would be to use something like
be16bacd 467C<sub base :Path :Args(0) {...}> (where the C<...> refers to the login
468code shown in C<sub index : Private> above). We are using C<sub base
469:Path :Args(0) {...}> here to specifically match the URL C</login>.
470C<Path> actions (aka, "literal actions") create URI matches relative to
471the namespace of the controller where they are defined. Although
472C<Path> supports arguments that allow relative and absolute paths to be
473defined, here we use an empty C<Path> definition to match on just the
474name of the controller itself. The method name, C<base>, is arbitrary.
475We make the match even more specific with the C<:Args(0)> action
476modifier -- this forces the match on I<only> C</login>, not
477C</login/somethingelse>.
478
7d310f12 479Next, update the corresponding method in C<lib/MyApp/Controller/Logout.pm>
480to match:
4d583dd8 481
7d310f12 482 =head2 index
4d583dd8 483
484 Logout logic
485
486 =cut
487
be16bacd 488 sub index : Private {
4d583dd8 489 my ($self, $c) = @_;
490
491 # Clear the user's state
492 $c->logout;
493
71dedf57 494 # Send the user to the starting point
4d583dd8 495 $c->response->redirect($c->uri_for('/'));
496 }
497
be16bacd 498As with the login controller, be sure to delete the
499C<$c->response->body('Matched MyApp::Controller::Logout in Logout.');>
500line of the C<sub index>.
7e5eb02c 501
4d583dd8 502
503=head2 Add a Login Form TT Template Page
504
505Create a login form by opening C<root/src/login.tt2> and inserting:
506
507 [% META title = 'Login' %]
508
509 <!-- Login form -->
510 <form method="post" action=" [% Catalyst.uri_for('/login') %] ">
511 <table>
512 <tr>
513 <td>Username:</td>
514 <td><input type="text" name="username" size="40" /></td>
515 </tr>
516 <tr>
517 <td>Password:</td>
518 <td><input type="password" name="password" size="40" /></td>
519 </tr>
520 <tr>
521 <td colspan="2"><input type="submit" name="submit" value="Submit" /></td>
522 </tr>
523 </table>
524 </form>
525
526
527=head2 Add Valid User Check
528
64ccd8a8 529We need something that provides enforcement for the authentication
530mechanism -- a I<global> mechanism that prevents users who have not
531passed authentication from reaching any pages except the login page.
532This is generally done via an C<auto> action/method (prior to Catalyst
533v5.66, this sort of thing would go in C<MyApp.pm>, but starting in
534v5.66, the preferred location is C<lib/MyApp/Controller/Root.pm>).
4d583dd8 535
71dedf57 536Edit the existing C<lib/MyApp/Controller/Root.pm> class file and insert
537the following method:
4d583dd8 538
539 =head2 auto
540
541 Check if there is a user and, if not, forward to login page
542
543 =cut
544
545 # Note that 'auto' runs after 'begin' but before your actions and that
546 # 'auto' "chain" (all from application path to most specific class are run)
547 sub auto : Private {
548 my ($self, $c) = @_;
549
23645266 550 # Allow unauthenticated users to reach the login page. This
551 # allows anauthenticated users to reach any action in the Login
552 # controller. To lock it down to a single action, we could use:
553 # if ($c->action eq $c->controller('Login')->action_for('index'))
554 # to only allow unauthenticated access to the C<index> action we
555 # added above.
556 if ($c->controller eq $c->controller('Login')) {
4d583dd8 557 return 1;
558 }
559
560 # If a user doesn't exist, force login
561 if (!$c->user_exists) {
562 # Dump a log message to the development server debug output
563 $c->log->debug('***Root::auto User not found, forwarding to /login');
564 # Redirect the user to the login page
565 $c->response->redirect($c->uri_for('/login'));
566 # Return 0 to cancel 'post-auto' processing and prevent use of application
567 return 0;
568 }
569
570 # User found, so return 1 to continue with processing after this 'auto'
571 return 1;
572 }
573
64ccd8a8 574B<Note:> Catalyst provides a number of different types of actions, such
575as C<Local>, C<Regex>, and C<Private>. You should refer to
71dedf57 576L<Catalyst::Manual::Intro> for a more detailed explanation, but the
577following bullet points provide a quick introduction:
4d583dd8 578
579=over 4
580
581=item *
582
64ccd8a8 583The majority of application use C<Local> actions for items that respond
584to user requests and C<Private> actions for those that do not directly
585respond to user input.
4d583dd8 586
587=item *
588
64ccd8a8 589There are five types of C<Private> actions: C<begin>, C<end>,
590C<default>, C<index>, and C<auto>.
4d583dd8 591
592=item *
593
a63e6e67 594Unlike the other actions where only a single method is called for each
595request, I<every> auto action along the chain of namespaces will be
596called.
4d583dd8 597
598=back
599
64ccd8a8 600By placing the authentication enforcement code inside the C<auto> method
601of C<lib/MyApp/Controller/Root.pm> (or C<lib/MyApp.pm>), it will be
602called for I<every> request that is received by the entire application.
4d583dd8 603
a63e6e67 604
4d583dd8 605=head2 Displaying Content Only to Authenticated Users
606
64ccd8a8 607Let's say you want to provide some information on the login page that
608changes depending on whether the user has authenticated yet. To do
609this, open C<root/src/login.tt2> in your editor and add the following
610lines to the bottom of the file:
4d583dd8 611
612 <p>
613 [%
614 # This code illustrates how certain parts of the TT
615 # template will only be shown to users who have logged in
616 %]
617 [% IF Catalyst.user %]
618 Please Note: You are already logged in as '[% Catalyst.user.username %]'.
619 You can <a href="[% Catalyst.uri_for('/logout') %]">logout</a> here.
620 [% ELSE %]
621 You need to log in to use this application.
622 [% END %]
623 [%#
624 Note that this whole block is a comment because the "#" appears
625 immediate after the "[%" (with no spaces in between). Although it
626 can be a handy way to temporarily "comment out" a whole block of
627 TT code, it's probably a little too subtle for use in "normal"
628 comments.
629 %]
630
64ccd8a8 631Although most of the code is comments, the middle few lines provide a
632"you are already logged in" reminder if the user returns to the login
633page after they have already authenticated. For users who have not yet
634authenticated, a "You need to log in..." message is displayed (note the
635use of an IF-THEN-ELSE construct in TT).
4d583dd8 636
637
638=head2 Try Out Authentication
639
64ccd8a8 640Press C<Ctrl-C> to kill the previous server instance (if it's still
641running) and restart it:
4d583dd8 642
643 $ script/myapp_server.pl
644
64ccd8a8 645B<IMPORTANT NOTE>: If you happen to be using Internet Explorer, you may
646need to use the command C<script/myapp_server.pl -k> to enable the
647keepalive feature in the development server. Otherwise, the HTTP
648redirect on successful login may not work correctly with IE (it seems to
649work without -k if you are running the web browser and development
650server on the same machine). If you are using browser a browser other
651than IE, it should work either way. If you want to make keepalive the
652default, you can edit C<script/myapp_server.pl> and change the
653initialization value for C<$keepalive> to C<1>. (You will need to do
654this every time you create a new Catalyst application or rebuild the
655C<myapp_server.pl> script.)
656
657Now trying going to L<http://localhost:3000/books/list> and you should
658be redirected to the login page, hitting Shift+Reload if necessary (the
659"You are already logged in" message should I<not> appear -- if it does,
71dedf57 660click the C<logout> button and try again). Note the C<***Root::auto User
661not found...> debug message in the development server output. Enter
662username C<test01> and password C<mypass>, and you should be taken to
663the Book List page.
4d583dd8 664
71dedf57 665Open C<root/src/books/list.tt2> and add the following lines to the
666bottom:
4d583dd8 667
668 <p>
669 <a href="[% Catalyst.uri_for('/login') %]">Login</a>
670 <a href="[% Catalyst.uri_for('form_create') %]">Create</a>
671 </p>
672
be16bacd 673Reload your browser and you should now see a "Login" and "Create" links
674at the bottom of the page (as mentioned earlier, you can update template
675files without reloading the development server). Click the first link
676to return to the login page. This time you I<should> see the "You are
677already logged in" message.
4d583dd8 678
64ccd8a8 679Finally, click the C<You can logout here> link on the C</login> page.
680You should stay at the login page, but the message should change to "You
681need to log in to use this application."
4d583dd8 682
683
4d583dd8 684=head1 USING PASSWORD HASHES
685
64ccd8a8 686In this section we increase the security of our system by converting
687from cleartext passwords to SHA-1 password hashes.
4d583dd8 688
64ccd8a8 689B<Note:> This section is optional. You can skip it and the rest of the
690tutorial will function normally.
4d583dd8 691
64ccd8a8 692Note that even with the techniques shown in this section, the browser
693still transmits the passwords in cleartext to your application. We are
694just avoiding the I<storage> of cleartext passwords in the database by
71dedf57 695using a SHA-1 hash. If you are concerned about cleartext passwords
696between the browser and your application, consider using SSL/TLS, made
a63e6e67 697easy with the Catalyst plugin
698L<Catalyst::Plugin:RequireSSL|Catalyst::Plugin:RequireSSL>.
699
4d583dd8 700
701=head2 Get a SHA-1 Hash for the Password
702
64ccd8a8 703Catalyst uses the C<Digest> module to support a variety of hashing
704algorithms. Here we will use SHA-1 (SHA = Secure Hash Algorithm).
705First, we should compute the SHA-1 hash for the "mypass" password we are
706using. The following command-line Perl script provides a "quick and
707dirty" way to do this:
4d583dd8 708
709 $ perl -MDigest::SHA -e 'print Digest::SHA::sha1_hex("mypass"), "\n"'
710 e727d1464ae12436e899a726da5b2f11d8381b26
711 $
712
cc548726 713B<Note:> You should probably modify this code for production use to
714not read the password from the command line. By having the script
715prompt for the cleartext password, it avoids having the password linger
716in forms such as your C<.bash_history> files (assuming you are using
717BASH as your shell). An example of such a script can be found in
718Appendix 3.
719
a63e6e67 720
4d583dd8 721=head2 Switch to SHA-1 Password Hashes in the Database
722
64ccd8a8 723Next, we need to change the C<password> column of our C<users> table to
724store this hash value vs. the existing cleartext password. Open
725C<myapp03.sql> in your editor and enter:
4d583dd8 726
727 --
728 -- Convert passwords to SHA-1 hashes
729 --
730 UPDATE users SET password = 'e727d1464ae12436e899a726da5b2f11d8381b26' WHERE id = 1;
731 UPDATE users SET password = 'e727d1464ae12436e899a726da5b2f11d8381b26' WHERE id = 2;
732 UPDATE users SET password = 'e727d1464ae12436e899a726da5b2f11d8381b26' WHERE id = 3;
733
734Then use the following command to update the SQLite database:
735
736 $ sqlite3 myapp.db < myapp03.sql
737
64ccd8a8 738B<Note:> We are using SHA-1 hashes here, but many other hashing
739algorithms are supported. See C<Digest> for more information.
4d583dd8 740
a63e6e67 741
64ccd8a8 742=head2 Enable SHA-1 Hash Passwords in
743C<Catalyst::Plugin::Authentication::Store::DBIC>
4d583dd8 744
64ccd8a8 745Edit C<myapp.yml> and update it to match (the C<password_type> and
746C<password_hash_type> are new, everything else is the same):
4d583dd8 747
748 ---
749 name: MyApp
750 authentication:
751 dbic:
752 # Note this first definition would be the same as setting
753 # __PACKAGE__->config->{authentication}->{dbic}->{user_class} = 'MyAppDB::User'
754 # in lib/MyApp.pm (IOW, each hash key becomes a "name:" in the YAML file).
755 #
756 # This is the model object created by Catalyst::Model::DBIC from your
757 # schema (you created 'MyAppDB::User' but as the Catalyst startup
758 # debug messages show, it was loaded as 'MyApp::Model::MyAppDB::User').
23645266 759 # NOTE: Omit 'MyApp::Model' here just as you would when using
760 # '$c->model("MyAppDB::User)'
4d583dd8 761 user_class: MyAppDB::User
762 # This is the name of the field in your 'users' table that contains the user's name
763 user_field: username
764 # This is the name of the field in your 'users' table that contains the password
765 password_field: password
766 # Other options can go here for hashed passwords
767 # Enabled hashed passwords
768 password_type: hashed
769 # Use the SHA-1 hashing algorithm
770 password_hash_type: SHA-1
771
772
773=head2 Try Out the Hashed Passwords
774
64ccd8a8 775Press C<Ctrl-C> to kill the previous server instance (if it's still
776running) and restart it:
4d583dd8 777
778 $ script/myapp_server.pl
779
64ccd8a8 780You should now be able to go to L<http://localhost:3000/books/list> and
781login as before. When done, click the "Logout" link on the login page
782(or point your browser at L<http://localhost:3000/logout>).
4d583dd8 783
be16bacd 784B<Note:> If you receive the debug screen in your browser with a
785C<Can't call method "stash" on an undefined value...> error message,
786make sure that you are using v0.07 of
787L<Catalyst::Plugin::Authorization::ACL|Catalyst::Plugin::Authorization::ACL>.
788The following command can be a useful way to quickly dump the version number
789of this module on your system:
790
791 perl -MCatalyst::Plugin::Authorization::ACL -e 'print $Catalyst::Plugin::Authorization::ACL::VERSION, "\n";'
792
a63e6e67 793
4d583dd8 794=head1 AUTHOR
795
796Kennedy Clark, C<hkclark@gmail.com>
797
eed93301 798Please report any errors, issues or suggestions to the author. The
7d310f12 799most recent version of the Catalyst Tutorial can be found at
eed93301 800L<http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/>.
4d583dd8 801
a63e6e67 802Copyright 2006, Kennedy Clark, under Creative Commons License
803(L<http://creativecommons.org/licenses/by-nc-sa/2.5/>).