Commit | Line | Data |
4d583dd8 |
1 | =head1 NAME |
2 | |
3 | Catalyst::Manual::Tutorial::Authentication - Catalyst Tutorial Part 4: Authentication |
4 | |
5 | |
6 | |
7 | =head1 OVERVIEW |
8 | |
9 | This is B<Part 4 of 9> for the Catalyst tutorial. |
10 | |
11 | L<Totorial Overview|Catalyst::Manual::Tutorial> |
12 | |
13 | =over 4 |
14 | |
15 | =item 1 |
16 | |
17 | L<Introduction|Catalyst::Manual::Tutorial::Intro> |
18 | |
19 | =item 2 |
20 | |
21 | L<Catalyst Basics|Catalyst::Manual::Tutorial::CatalystBasics> |
22 | |
23 | =item 3 |
24 | |
25 | L<Basic CRUD|Catalyst::Manual::Tutorial03_BasicCRUD> |
26 | |
27 | =item 4 |
28 | |
29 | B<Authentication> |
30 | |
31 | =item 5 |
32 | |
33 | L<Authorization|Catalyst::Manual::Tutorial::Authorization> |
34 | |
35 | =item 6 |
36 | |
37 | L<Debugging|Catalyst::Manual::Tutorial::Debugging> |
38 | |
39 | =item 7 |
40 | |
41 | L<Testing|Catalyst::Manual::Tutorial::Testing> |
42 | |
43 | =item 8 |
44 | |
45 | L<AdvancedCRUD|Catalyst::Manual::Tutorial::AdvancedCRUD> |
46 | |
47 | =item 9 |
48 | |
49 | L<Appendicies|Catalyst::Manual::Tutorial::Appendicies> |
50 | |
51 | =back |
52 | |
53 | |
54 | |
55 | =head1 DESCRIPTION |
56 | |
57 | Now that we finally have a simple yet functional application, we can focus on providing authentication (with authorization coming in Part 5). |
58 | |
59 | This part of the tutorial is divided into two main sections: 1) basic, cleartext authentication and 2) hash-based authentication. |
60 | |
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: |
62 | |
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. |
65 | |
66 | |
67 | |
68 | =head1 BASIC AUTHENTICATION |
69 | |
70 | This section explores how add authentication logic to a Catalyst application. |
71 | |
72 | |
73 | =head2 Add Users and Roles to the Database |
74 | |
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: |
76 | |
77 | -- |
78 | -- Add users and roles tables, along with a many-to-many join table |
79 | -- |
80 | CREATE TABLE users ( |
81 | id INTEGER PRIMARY KEY, |
82 | username TEXT, |
83 | password TEXT, |
84 | email_address TEXT, |
85 | first_name TEXT, |
86 | last_name TEXT, |
87 | active INTEGER |
88 | ); |
89 | CREATE TABLE roles ( |
90 | id INTEGER PRIMARY KEY, |
91 | role TEXT |
92 | ); |
93 | CREATE TABLE user_roles ( |
94 | user_id INTEGER, |
95 | role_id INTEGER, |
96 | PRIMARY KEY (user_id, role_id) |
97 | ); |
98 | -- |
99 | -- Load up some initial test data |
100 | -- |
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); |
110 | |
111 | Then load this into the C<myapp.db> database with the following command: |
112 | |
113 | $ sqlite3 myapp.db < myapp02.sql |
114 | |
115 | |
116 | =head2 Add User and Role Information to Dbic Schema |
117 | |
118 | This step adds DBIC-based classes for the user-related database tables (the role information will not be used until the Part 5): |
119 | |
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): |
121 | |
122 | package MyAppDB; |
123 | |
124 | =head1 NAME |
125 | |
126 | MyAppDB -- DBIC Schema Class |
127 | |
128 | =cut |
129 | |
130 | # Our schema needs to inherit from 'DBIx::Class::Schema' |
131 | use base qw/DBIx::Class::Schema/; |
132 | |
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/] |
143 | }); |
144 | |
145 | 1; |
146 | |
147 | |
148 | =head2 Create New "Result Source Objects" |
149 | |
150 | Create the following three files with the content shown below. |
151 | |
152 | C<lib/MyAppDB/User.pm>: |
153 | |
154 | package MyAppDB::User; |
155 | |
156 | use base qw/DBIx::Class/; |
157 | |
158 | # Load required DBIC stuff |
159 | __PACKAGE__->load_components(qw/PK::Auto Core/); |
160 | # Set the table name |
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'); |
166 | |
167 | # |
168 | # Set relationships: |
169 | # |
170 | |
171 | # has_many(): |
172 | # args: |
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'); |
177 | |
178 | |
179 | =head1 NAME |
180 | |
181 | MyAppDB::User - A model object representing a person with access to the system. |
182 | |
183 | =head1 DESCRIPTION |
184 | |
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. |
187 | |
188 | For Catalyst, this is designed to be used through MyApp::Model::MyAppDB. |
189 | Offline utilities may wish to use this class directly. |
190 | |
191 | =cut |
192 | |
193 | 1; |
194 | |
195 | |
196 | C<lib/MyAppDB/Role.pm>: |
197 | |
198 | package MyAppDB::Role; |
199 | |
200 | use base qw/DBIx::Class/; |
201 | |
202 | # Load required DBIC stuff |
203 | __PACKAGE__->load_components(qw/PK::Auto Core/); |
204 | # Set the table name |
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'); |
210 | |
211 | # |
212 | # Set relationships: |
213 | # |
214 | |
215 | # has_many(): |
216 | # args: |
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'); |
221 | |
222 | |
223 | =head1 NAME |
224 | |
225 | MyAppDB::Role - A model object representing a class of access permissions to |
226 | the system. |
227 | |
228 | =head1 DESCRIPTION |
229 | |
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. |
232 | |
233 | For Catalyst, this is designed to be used through MyApp::Model::MyAppDB. |
234 | "Offline" utilities may wish to use this class directly. |
235 | |
236 | =cut |
237 | |
238 | 1; |
239 | |
240 | |
241 | C<lib/MyAppDB/UserRole.pm>: |
242 | |
243 | package MyAppDB::UserRole; |
244 | |
245 | use base qw/DBIx::Class/; |
246 | |
247 | # Load required DBIC stuff |
248 | __PACKAGE__->load_components(qw/PK::Auto Core/); |
249 | # Set the table name |
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/); |
255 | |
256 | # |
257 | # Set relationships: |
258 | # |
259 | |
260 | # belongs_to(): |
261 | # args: |
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'); |
266 | |
267 | # belongs_to(): |
268 | # args: |
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'); |
273 | |
274 | |
275 | =head1 NAME |
276 | |
277 | MyAppDB::UserRole - A model object representing the JOIN between Users and Roles. |
278 | |
279 | =head1 DESCRIPTION |
280 | |
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. |
283 | |
284 | You probably won't need to use this class directly -- it will be automatically |
285 | used by DBIC where joins are needed. |
286 | |
287 | For Catalyst, this is designed to be used through MyApp::Model::MyAppDB. |
288 | Offline utilities may wish to use this class directly. |
289 | |
290 | =cut |
291 | |
292 | 1; |
293 | |
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. |
295 | |
296 | |
297 | =head2 Sanity-Check Reload of Development Server |
298 | |
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: |
300 | |
301 | $ script/myapp_server.pl |
302 | |
303 | Look for the three new model objects in the startup debug output: |
304 | |
305 | ... |
306 | .-------------------------------------------------------------------+----------. |
307 | | Class | Type | |
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 | '-------------------------------------------------------------------+----------' |
320 | ... |
321 | |
322 | Again, notice that your "result source" classes have been "re-loaded" by Catalyst under C<MyApp::Model>. |
323 | |
324 | |
325 | =head2 Include Authentication and Session Plugins |
326 | |
327 | Edit C<lib/MyApp.pm> and update it as follows (everything below C<DefaultEnd> is new): |
328 | |
329 | use Catalyst qw/ |
330 | -Debug |
331 | ConfigLoader |
332 | Static::Simple |
333 | |
334 | Dumper |
335 | StackTrace |
336 | DefaultEnd |
337 | |
338 | Authentication |
339 | Authentication::Store::DBIC |
340 | Authentication::Credential::Password |
341 | |
342 | Session |
343 | Session::Store::FastMmap |
344 | Session::State::Cookie |
345 | /; |
346 | |
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. |
348 | |
349 | |
350 | =head2 Configure Authentication |
351 | |
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. |
353 | |
354 | Edit the C<myapp.yml> YAML and update it to match: |
355 | |
356 | --- |
357 | name: MyApp |
358 | authentication: |
359 | dbic: |
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). |
363 | # |
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 |
370 | user_field: username |
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 |
374 | |
375 | Inline comments in the code above explain how each field is being used. |
376 | |
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). |
378 | |
379 | |
380 | =head2 Add Login and Logout Controllers |
381 | |
382 | Use the Catalyst create script to create two stub controller files: |
383 | |
384 | $ script/myapp_create.pl controller Login |
385 | $ script/myapp_create.pl controller Logout |
386 | |
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. |
388 | |
389 | Then open C<lib/MyApp/Controller/Login.pm> and add: |
390 | |
391 | =head2 default |
392 | |
393 | Login logic |
394 | |
395 | =cut |
396 | |
397 | sub default : Private { |
398 | my ($self, $c) = @_; |
399 | |
400 | # Get the username and password from form |
401 | my $username = $c->request->params->{username} || ""; |
402 | my $password = $c->request->params->{password} || ""; |
403 | |
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')); |
410 | return; |
411 | } else { |
412 | # Set an error message |
413 | $c->stash->{error_msg} = "Bad username or password."; |
414 | } |
415 | } |
416 | |
417 | # If either of above don't work out, send to the login page |
418 | $c->stash->{template} = 'login.tt2'; |
419 | } |
420 | |
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. |
422 | |
423 | Next, create a corresponding method in C<lib/MyApp/Controller/Logout.pm>: |
424 | |
425 | =head2 default |
426 | |
427 | Logout logic |
428 | |
429 | =cut |
430 | |
431 | sub default : Private { |
432 | my ($self, $c) = @_; |
433 | |
434 | # Clear the user's state |
435 | $c->logout; |
436 | |
437 | # Send the user to the starting |
438 | $c->response->redirect($c->uri_for('/')); |
439 | } |
440 | |
441 | |
442 | =head2 Add a Login Form TT Template Page |
443 | |
444 | Create a login form by opening C<root/src/login.tt2> and inserting: |
445 | |
446 | [% META title = 'Login' %] |
447 | |
448 | <!-- Login form --> |
449 | <form method="post" action=" [% Catalyst.uri_for('/login') %] "> |
450 | <table> |
451 | <tr> |
452 | <td>Username:</td> |
453 | <td><input type="text" name="username" size="40" /></td> |
454 | </tr> |
455 | <tr> |
456 | <td>Password:</td> |
457 | <td><input type="password" name="password" size="40" /></td> |
458 | </tr> |
459 | <tr> |
460 | <td colspan="2"><input type="submit" name="submit" value="Submit" /></td> |
461 | </tr> |
462 | </table> |
463 | </form> |
464 | |
465 | |
466 | =head2 Add Valid User Check |
467 | |
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>). |
469 | |
470 | Edit the existing C<lib/MyApp/Controller/Root.pm> class file and insert the following method: |
471 | |
472 | =head2 auto |
473 | |
474 | Check if there is a user and, if not, forward to login page |
475 | |
476 | =cut |
477 | |
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) |
480 | sub auto : Private { |
481 | my ($self, $c) = @_; |
482 | |
483 | # Allow unauthenticated users to reach the login page |
484 | if ($c->request->path =~ /login/) { |
485 | return 1; |
486 | } |
487 | |
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 |
495 | return 0; |
496 | } |
497 | |
498 | # User found, so return 1 to continue with processing after this 'auto' |
499 | return 1; |
500 | } |
501 | |
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: |
503 | |
504 | =over 4 |
505 | |
506 | =item * |
507 | |
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. |
509 | |
510 | =item * |
511 | |
512 | There are five types of C<Private> actions: C<begin>, C<end>, C<default>, C<index>, and C<auto>. |
513 | |
514 | =item * |
515 | |
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. |
517 | |
518 | =back |
519 | |
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. |
521 | |
522 | |
523 | =head2 Displaying Content Only to Authenticated Users |
524 | |
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: |
526 | |
527 | <p> |
528 | [% |
529 | # This code illustrates how certain parts of the TT |
530 | # template will only be shown to users who have logged in |
531 | %] |
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. |
535 | [% ELSE %] |
536 | You need to log in to use this application. |
537 | [% END %] |
538 | [%# |
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" |
543 | comments. |
544 | %] |
545 | |
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). |
547 | |
548 | |
549 | =head2 Try Out Authentication |
550 | |
551 | Press C<Ctrl-C> to kill the previous server instance (if it's still running) and |
552 | restart it: |
553 | |
554 | $ script/myapp_server.pl |
555 | |
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.) |
557 | |
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. |
559 | |
560 | Open C< root/src/books/list.tt2> and add the following lines to the bottom: |
561 | |
562 | <p> |
563 | <a href="[% Catalyst.uri_for('/login') %]">Login</a> |
564 | <a href="[% Catalyst.uri_for('form_create') %]">Create</a> |
565 | </p> |
566 | |
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. |
568 | |
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." |
570 | |
571 | |
572 | |
573 | =head1 USING PASSWORD HASHES |
574 | |
575 | In this section we increase the security of our system by converting from cleartext passwords to SHA-1 password hashes. |
576 | |
577 | B<Note:> This section is optional. You can skip it and the rest of the tutorial will function normally. |
578 | |
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. |
580 | |
581 | |
582 | =head2 Get a SHA-1 Hash for the Password |
583 | |
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: |
585 | |
586 | $ perl -MDigest::SHA -e 'print Digest::SHA::sha1_hex("mypass"), "\n"' |
587 | e727d1464ae12436e899a726da5b2f11d8381b26 |
588 | $ |
589 | |
590 | |
591 | =head2 Switch to SHA-1 Password Hashes in the Database |
592 | |
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: |
594 | |
595 | -- |
596 | -- Convert passwords to SHA-1 hashes |
597 | -- |
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; |
601 | |
602 | Then use the following command to update the SQLite database: |
603 | |
604 | $ sqlite3 myapp.db < myapp03.sql |
605 | |
606 | B<Note:> We are using SHA-1 hashes here, but many other hashing algorithms are supported. See C<Digest > for more information. |
607 | |
608 | |
609 | =head2 Enable SHA-1 Hash Passwords in C<Catalyst::Plugin::Authentication::Store::DBIC> |
610 | |
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): |
612 | |
613 | --- |
614 | name: MyApp |
615 | authentication: |
616 | dbic: |
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). |
620 | # |
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 |
627 | user_field: username |
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 |
635 | |
636 | |
637 | =head2 Try Out the Hashed Passwords |
638 | |
639 | Press C<Ctrl-C> to kill the previous server instance (if it's still running) and restart it: |
640 | |
641 | $ script/myapp_server.pl |
642 | |
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>). |
644 | |
645 | |
646 | |
647 | =head1 AUTHOR |
648 | |
649 | Kennedy Clark, C<hkclark@gmail.com> |
650 | |
651 | Please report any errors, issues or suggestions to the author. |
652 | |
653 | Copyright 2006, Kennedy Clark. All rights reserved. |
654 | |
655 | This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. |
656 | |
657 | Version: .94 |
658 | |