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