Expanded tests a little to start account for failures/fatals.
[catagits/Catalyst-Authentication-Credential-OpenID.git] / lib / Catalyst / Authentication / Credential / OpenID.pm
1 package Catalyst::Authentication::Credential::OpenID;
2 use strict;
3 # use warnings; no warnings "uninitialized"; # for testing, not production
4 use parent "Class::Accessor::Fast";
5
6 BEGIN {
7     __PACKAGE__->mk_accessors(qw/ _config realm debug secret /);
8 }
9
10 our $VERSION = "0.14_03";
11
12 use Net::OpenID::Consumer;
13 use Catalyst::Exception ();
14
15 sub new : method {
16     my ( $class, $config, $c, $realm ) = @_;
17     my $self = { _config => { %{ $config },
18                               %{ $realm->{config} }
19                           }
20                  };
21     bless $self, $class;
22
23     # 2.0 spec says "SHOULD" be named "openid_identifier."
24     $self->_config->{openid_field} ||= "openid_identifier";
25
26     $self->debug( $self->_config->{debug} );
27
28     my $secret = $self->_config->{consumer_secret} ||= join("+",
29                                                             __PACKAGE__,
30                                                             $VERSION,
31                                                             sort keys %{ $c->config }
32                                                             );
33
34     $secret = substr($secret,0,255) if length $secret > 255;
35     $self->secret($secret);
36     # If user has no preference we prefer L::PA b/c it can prevent DoS attacks.
37     $self->_config->{ua_class} ||= eval "use LWPx::ParanoidAgent" ?
38         "LWPx::ParanoidAgent" : "LWP::UserAgent";
39
40     my $agent_class = $self->_config->{ua_class};
41     eval "require $agent_class"
42         or Catalyst::Exception->throw("Could not 'require' user agent class " .
43                                       $self->_config->{ua_class});
44
45     $c->log->debug("Setting consumer secret: " . $secret) if $self->debug;
46
47     return $self;
48 }
49
50 sub authenticate : method {
51     my ( $self, $c, $realm, $authinfo ) = @_;
52
53     $c->log->debug("authenticate() called from " . $c->request->uri) if $self->debug;
54
55     my $field = $self->{_config}->{openid_field};
56
57     my $claimed_uri = $authinfo->{ $field };
58
59     # Its security related so we want to be explicit about GET/POST param retrieval.
60     $claimed_uri ||= $c->req->method eq 'GET' ? 
61         $c->req->query_params->{ $field } : $c->req->body_params->{ $field };
62
63     my $csr = Net::OpenID::Consumer->new(
64         ua => $self->_config->{ua_class}->new(%{$self->_config->{ua_args} || {}}),
65         args => $c->req->params,
66         consumer_secret => $self->secret,
67     );
68
69     my @extensions = $self->_config->{extensions} ?
70         @{ $self->_config->{extensions} } : $self->_config->{extension_args} ?
71         @{ $self->_config->{extension_args} } : ();
72
73     if ( $claimed_uri )
74     {
75         my $current = $c->uri_for($c->req->uri->path); # clear query/fragment...
76
77         my $identity = $csr->claimed_identity($claimed_uri);
78         unless ( $identity )
79         {
80             Catalyst::Exception->throw($csr->err);
81         }
82
83         $identity->set_extension_args(@extensions)
84             if @extensions;
85
86         my $check_url = $identity->check_url(
87             return_to  => $current . '?openid-check=1',
88             trust_root => $current,
89             delayed_return => 1,
90         );
91         $c->res->redirect($check_url);
92         $c->detach();
93     }
94     elsif ( $c->req->params->{'openid-check'} )
95     {
96         if ( my $setup_url = $csr->user_setup_url )
97         {
98             $c->res->redirect($setup_url);
99             return;
100         }
101         elsif ( $csr->user_cancel )
102         {
103             return;
104         }
105         elsif ( my $identity = $csr->verified_identity )
106         {
107             # This is where we ought to build an OpenID user and verify against the spec.
108             my $user = +{ map { $_ => scalar $identity->$_ }
109                 qw( url display rss atom foaf declared_rss declared_atom declared_foaf foafmaker ) };
110             # Dude, I did not design the array as hash spec. Don't curse me [apv].
111             my %flat = @extensions;
112             for my $key ( keys %flat )
113             {
114                 $user->{extensions}->{$key} = $identity->signed_extension_fields($key);
115             }
116
117             my $user_obj = $realm->find_user($user, $c);
118
119             if ( ref $user_obj )
120             {
121                 return $user_obj;
122             }
123             else
124             {
125                 $c->log->debug("Verified OpenID identity failed to load with find_user; bad user_class? Try 'Null.'") if $c->debug;
126                 return;
127             }
128         }
129         else
130         {
131             Catalyst::Exception->throw("Error validating identity: " .
132                                        $csr->err);
133         }
134     }
135     return;
136 }
137
138 1;
139
140 __END__
141
142 =head1 NAME
143
144 Catalyst::Authentication::Credential::OpenID - OpenID credential for Catalyst::Plugin::Authentication framework.
145
146 =head1 VERSION
147
148 0.14_03
149
150 =head1 BACKWARDS COMPATIBILITY CHANGE
151
152 B<NB>: The extenstions were previously configured under the key C<extension_args>. They are now configured under C<extensions>. This prevents the need for double configuration but it breaks extensions in your application if you do not change the name. The old version is supported for now but may be phased out at any time.
153
154 As previously noted, L</EXTENSIONS TO OPENID>, I have not tested the extensions. I would be grateful for any feedback or, better, tests.
155
156 =head1 SYNOPSIS
157
158 In MyApp.pm-
159
160  use Catalyst qw/
161     Authentication
162     Session
163     Session::Store::FastMmap
164     Session::State::Cookie
165  /;
166
167 Somewhere in myapp.conf-
168
169  <Plugin::Authentication>
170      default_realm   openid
171      <realms>
172          <openid>
173              <credential>
174                  class   OpenID
175              </credential>
176              ua_class   LWP::UserAgent
177          </openid>
178      </realms>
179  </Plugin::Authentication>
180
181 Or in your myapp.yml if you're using L<YAML> instead-
182
183  Plugin::Authentication:
184    default_realm: openid
185    realms:
186      openid:
187        credential:
188          class: OpenID
189        ua_class: LWP::UserAgent
190
191 In a controller, perhaps C<Root::openid>-
192
193  sub openid : Local {
194       my($self, $c) = @_;
195
196       if ( $c->authenticate() )
197       {
198           $c->flash(message => "You signed in with OpenID!");
199           $c->res->redirect( $c->uri_for('/') );
200       }
201       else
202       {
203           # Present OpenID form.
204       }
205  }
206
207 And a L<Template> to match in C<openid.tt>-
208
209  <form action="[% c.uri_for('/openid') %]" method="GET" name="openid">
210  <input type="text" name="openid_identifier" class="openid" />
211  <input type="submit" value="Sign in with OpenID" />
212  </form>
213
214 =head1 DESCRIPTION
215
216 This is the B<third> OpenID related authentication piece for
217 L<Catalyst>. The first E<mdash> L<Catalyst::Plugin::Authentication::OpenID>
218 by Benjamin Trott E<mdash> was deprecated by the second E<mdash>
219 L<Catalyst::Plugin::Authentication::Credential::OpenID> by Tatsuhiko
220 Miyagawa E<mdash> and this is an attempt to deprecate both by conforming to
221 the newish, at the time of this module's inception, realm-based
222 authentication in L<Catalyst::Plugin::Authentication>.
223
224  1. Catalyst::Plugin::Authentication::OpenID
225  2. Catalyst::Plugin::Authentication::Credential::OpenID
226  3. Catalyst::Authentication::Credential::OpenID
227
228 The benefit of this version is that you can use an arbitrary number of
229 authentication systems in your L<Catalyst> application and configure
230 and call all of them in the same way.
231
232 Note that both earlier versions of OpenID authentication use the method
233 C<authenticate_openid()>. This module uses C<authenticate()> and
234 relies on you to specify the realm. You can specify the realm as the
235 default in the configuration or inline with each
236 C<authenticate()> call; more below.
237
238 This module functions quite differently internally from the others.
239 See L<Catalyst::Plugin::Authentication::Internals> for more about this
240 implementation.
241
242 =head1 METHODS
243
244 =over 4
245
246 =item $c->authenticate({},"your_openid_realm");
247
248 Call to authenticate the user via OpenID. Returns false if
249 authorization is unsuccessful. Sets the user into the session and
250 returns the user object if authentication succeeds.
251
252 You can see in the call above that the authentication hash is empty.
253 The implicit OpenID parameter is, as the 2.0 specification says it
254 SHOULD be, B<openid_identifier>. You can set it anything you like in
255 your realm configuration, though, under the key C<openid_field>. If
256 you call C<authenticate()> with the empty info hash and no configured
257 C<openid_field> then only C<openid_identifier> is checked.
258
259 It implicitly does this (sort of, it checks the request method too)-
260
261  my $claimed_uri = $c->req->params->{openid_identifier};
262  $c->authenticate({openid_identifier => $claimed_uri});
263
264 =item Catalyst::Authentication::Credential::OpenID->new()
265
266 You will never call this. Catalyst does it for you. The only important
267 thing you might like to know about it is that it merges its realm
268 configuration with its configuration proper. If this doesn't mean
269 anything to you, don't worry.
270
271 =back
272
273 =head2 USER METHODS
274
275 Currently the only supported user class is L<Catalyst::Plugin::Authentication::User::Hash>.
276
277 =over 4
278
279 =item $c->user->url
280
281 =item $c->user->display
282
283 =item $c->user->rss 
284
285 =item $c->user->atom
286
287 =item $c->user->foaf
288
289 =item $c->user->declared_rss
290
291 =item $c->user->declared_atom
292
293 =item $c->user->declared_foaf
294
295 =item $c->user->foafmaker
296
297 =back
298
299 See L<Net::OpenID::VerifiedIdentity> for details.
300
301 =head1 CONFIGURATION
302
303 Catalyst authentication is now configured entirely from your
304 application's configuration. Do not, for example, put
305 C<Credential::OpenID> into your C<use Catalyst ...> statement.
306 Instead, tell your application that in one of your authentication
307 realms you will use the credential.
308
309 In your application the following will give you two different
310 authentication realms. One called "members" which authenticates with
311 clear text passwords and one called "openid" which uses... uh, OpenID.
312
313  __PACKAGE__->config
314     ( name => "MyApp",
315       "Plugin::Authentication" => {
316           default_realm => "members",
317           realms => {
318               members => {
319                   credential => {
320                       class => "Password",
321                       password_field => "password",
322                       password_type => "clear"
323                       },
324                           store => {
325                               class => "Minimal",
326                               users => {
327                                   paco => {
328                                       password => "l4s4v3n7ur45",
329                                   },
330                               }
331                           }
332               },
333               openid => {
334                   consumer_secret => "Don't bother setting",
335                   ua_class => "LWP::UserAgent",
336                   ua_args => {
337                       whitelisted_hosts => [qw/ 127.0.0.1 localhost /],
338                   },
339                   credential => {
340                       class => "OpenID",
341                       store => {
342                           class => "OpenID",
343                       },
344                   },
345                   extensions => [
346                       'http://openid.net/extensions/sreg/1.1',
347                       {
348                        required => 'email',
349                        optional => 'fullname,nickname,timezone',
350                       },
351                   ],
352               },
353           },
354       }
355     );
356
357 This is the same configuration in the default L<Catalyst> configuration format from L<Config::General>.
358
359  name   MyApp
360  <Plugin::Authentication>
361      default_realm   members
362      <realms>
363          <members>
364              <store>
365                  class   Minimal
366                  <users>
367                      <paco>
368                          password   l4s4v3n7ur45
369                      </paco>
370                  </users>
371              </store>
372              <credential>
373                  password_field   password
374                  password_type   clear
375                  class   Password
376              </credential>
377          </members>
378          <openid>
379              <ua_args>
380                  whitelisted_hosts   127.0.0.1
381                  whitelisted_hosts   localhost
382              </ua_args>
383              consumer_secret   Don't bother setting
384              ua_class   LWP::UserAgent
385              <credential>
386                  <store>
387                      class   OpenID
388                  </store>
389                  class   OpenID
390              </credential>
391              <extensions>
392                  http://openid.net/extensions/sreg/1.1
393                  required   email
394                  optional   fullname,nickname,timezone
395              </extensions>
396          </openid>
397      </realms>
398  </Plugin::Authentication>
399
400 And now, the same configuration in L<YAML>. B<NB>: L<YAML> is whitespace sensitive.
401
402  name: MyApp
403  Plugin::Authentication:
404    default_realm: members
405    realms:
406      members:
407        credential:
408          class: Password
409          password_field: password
410          password_type: clear
411        store:
412          class: Minimal
413          users:
414            paco:
415              password: l4s4v3n7ur45
416      openid:
417        credential:
418          class: OpenID
419          store:
420            class: OpenID
421        consumer_secret: Don't bother setting
422        ua_class: LWP::UserAgent
423        ua_args:
424          whitelisted_hosts:
425            - 127.0.0.1
426            - localhost
427        extensions:
428            - http://openid.net/extensions/sreg/1.1
429            - required: email
430              optional: fullname,nickname,timezone
431
432 B<NB>: There is no OpenID store yet.
433
434 =head2 EXTENSIONS TO OPENID
435
436 The Simple Registration--L<http://openid.net/extensions/sreg/1.1>--(SREG) extension to OpenID is supported in the L<Net::OpenID> family now. Experimental support for it is included here as of v0.12. SREG is the only supported extension in OpenID 1.1. It's experimental in the sense it's a new interface and barely tested. Support for OpenID extensions is here to stay.
437
438 =head2 MORE ON CONFIGURATION
439
440 These are set in your realm. See above.
441
442 =over 4
443
444 =item ua_args and ua_class
445
446 L<LWPx::ParanoidAgent> is the default agent E<mdash> C<ua_class>
447 E<mdash> if it's available, L<LWP::UserAgent> if not. You don't have
448 to set it. I recommend that you do B<not> override it. You can with
449 any well behaved L<LWP::UserAgent>. You probably should not.
450 L<LWPx::ParanoidAgent> buys you many defenses and extra security
451 checks. When you allow your application users freedom to initiate
452 external requests, you open an avenue for DoS (denial of service)
453 attacks. L<LWPx::ParanoidAgent> defends against this.
454 L<LWP::UserAgent> and any regular subclass of it will not.
455
456 =item consumer_secret
457
458 The underlying L<Net::OpenID::Consumer> object is seeded with a
459 secret. If it's important to you to set your own, you can. The default
460 uses this package name + its version + the sorted configuration keys
461 of your Catalyst application (chopped at 255 characters if it's
462 longer). This should generally be superior to any fixed string.
463
464 =back
465
466 =head1 TODO
467
468 Option to suppress fatals.
469
470 Support more of the new methods in the L<Net::OpenID> kit.
471
472 There are some interesting implications with this sort of setup. Does
473 a user aggregate realms or can a user be signed in under more than one
474 realm? The documents could contain a recipe of the self-answering
475 OpenID end-point that is in the tests.
476
477 Debug statements need to be both expanded and limited via realm
478 configuration.
479
480 Better diagnostics in errors. Debug info at all consumer calls.
481
482 Roles from provider domains? Mapped? Direct? A generic "openid" auto_role?
483
484 =head1 THANKS
485
486 To Benjamin Trott (L<Catalyst::Plugin::Authentication::OpenID>), Tatsuhiko Miyagawa (L<Catalyst::Plugin::Authentication::Credential::OpenID>), Brad Fitzpatrick for the great OpenID stuff, Martin Atkins for picking up the code to handle OpenID 2.0, and Jay Kuri and everyone else who has made Catalyst such a wonderful framework.
487
488 Menno Blom provided a bug fix and the hook to use OpenID extensions.
489
490 =head1 LICENSE AND COPYRIGHT
491
492 Copyright (c) 2008-2009, Ashley Pond V C<< <ashley@cpan.org> >>. Some of Tatsuhiko Miyagawa's work is reused here.
493
494 This module is free software; you can redistribute it and modify it under the same terms as Perl itself. See L<perlartistic>.
495
496 =head1 DISCLAIMER OF WARRANTY
497
498 Because this software is licensed free of charge, there is no warranty
499 for the software, to the extent permitted by applicable law. Except when
500 otherwise stated in writing the copyright holders and other parties
501 provide the software "as is" without warranty of any kind, either
502 expressed or implied, including, but not limited to, the implied
503 warranties of merchantability and fitness for a particular purpose. The
504 entire risk as to the quality and performance of the software is with
505 you. Should the software prove defective, you assume the cost of all
506 necessary servicing, repair, or correction.
507
508 In no event unless required by applicable law or agreed to in writing
509 will any copyright holder, or any other party who may modify or
510 redistribute the software as permitted by the above license, be
511 liable to you for damages, including any general, special, incidental,
512 or consequential damages arising out of the use or inability to use
513 the software (including but not limited to loss of data or data being
514 rendered inaccurate or losses sustained by you or third parties or a
515 failure of the software to operate with any other software), even if
516 such holder or other party has been advised of the possibility of
517 such damages.
518
519 =head1 SEE ALSO
520
521 =over 4
522
523 =item OpenID
524
525 L<Net::OpenID::Server>, L<Net::OpenID::VerifiedIdentity>, L<Net::OpenID::Consumer>, L<http://openid.net/>, L<http://openid.net/developers/specs/>, and L<http://openid.net/extensions/sreg/1.1>.
526
527 =item Catalyst Authentication
528
529 L<Catalyst>, L<Catalyst::Plugin::Authentication>, L<Catalyst::Manual::Tutorial::Authorization>, and L<Catalyst::Manual::Tutorial::Authentication>.
530
531 =item Catalyst Configuration
532
533 L<Catalyst::Plugin::ConfigLoader>, L<Config::General>, and L<YAML>.
534
535 =item Miscellaneous
536
537 L<Catalyst::Manual::Tutorial>, L<Template>, L<LWPx::ParanoidAgent>.
538
539 =back
540
541 =cut