The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

LWP::Authen::OAuth2 - Make requests to OAuth2 APIs.

VERSION

Version 0.02

SYNOPSIS

OAuth 2 is a protocol that let's a user tell a service provider that a consumer has permission to use the service provider's APIs to do things that require access to the user's account. This module tries to make life easier for someone who wants to write a consumer in Perl.

Specifically it provides convenience methods for all of the requests that are made to the service provider as part of the permission handshake, and after that will proxy off of LWP::UserAgent to let you send properly authenticated requests to the API that you are trying to use. When possible, this will include transparent refresh/retry logic for access tokens expiration.

For a full explanation of OAuth 2, common terminology, the requests that get made, and the necessary tasks that this module does not address, please see LWP::Authen::OAuth2::Overview

This module will not help with OAuth 1. See the similarly named but unrelated LWP::Authen::OAuth for a module that can help with that.

Here are examples of simple usage.

    use LWP::Authen::OAuth2;

    # Constructor
    my $oauth2 = LWP::Authen::OAuth2->new(
                     client_id => "Public from service provider",
                     client_secret => "s3cr3t fr0m svc prov",
                     service_provider => "Google",
                     redirect_uri => "https://your.url.com/",

                     # Optional hook, but recommended.
                     save_tokens => \&save_tokens,

                     # This is for when you have tokens from last time.
                     token_string => $token_string.
                 );

    # URL for user to visit to start the process.
    my $url = $oauth2->authorization_url();

    # Get your tokens from the service provider.
    $oauth2->request_tokens(code => $code);

    # Get your token as a string you can easily store, pass around, etc.
    # If you passed in a save_tokens callback, that gets passed this.
    my $token_string = $oauth2->token_string,

    # Access the API.  Consult the service_provider's documentation for when
    # to do which.
    $oauth2->get($url, %values);
    $oauth2->post($url, %values);
    $oauth2->put($url, %values);
    $oauth2->delete($url, %values);
    $oauth2->head($url, %values);

    # In flows where you can't automatically refresh tokens, it is nice to
    # know when to send the user back to the authorization_url...
    $oauth2->should_refresh();

CONSTRUCTOR

When you call LWP::Authen::OAuth2-new(...)>, arguments are passed as a key/value list. They are processed in the following phases:

  • Construct service provider

  • Service provider collects arguments it wants

  • LWP::Authen::OAuth2 overrides defaults from arguments

  • Sanity check

Here are those phases in more detail.

  • Construct service provider

    There are two ways to construct a service provider.

    Prebuilt class

    To load a prebuilt class you just need one or two arguments.

    service_provider => $Foo,

    In the above construct, $Foo identifies the base class for your service provider. The actual class will be the first of the following two classes that can be loaded. Failure to find either is an error.

        LWP::Authen::OAuth2::ServiceProvider $Foo
        $Foo

    A list of prebuilt service provider classes is in LWP::Authen::OAuth2::ServiceProvider as well as instructions for making a new one.

    flow => $flow,

    Service providers can choose to provide multiple flows, with different client interactions. The base service provider class can support this by offering an optional flow argument to get the right behavior. See the service provider class for details.

    Built on the fly

    The behavior of simple service providers can be described on the fly without needing a prebuilt class. To do that, the following arguments can be filled with arguments from your service provider:

    authorization_endpoint => $auth_url,

    This is the URL which the user is directed to in the authorization request.

    token_endpoint => $token_url,

    This is the URL which the consumer goes to for tokens.

    Various optional fields

    LWP::Authen::OAuth2::ServiceProvider documents many methods that are available to customize the actual requests made, and defaults available. Simple service providers can likely get by without this, but here is a list of those methods that can be specified instead in the constructor:

        # Arrayrefs
        required_defaults
        more_defaults
        authorization_required_params
        authorization_more_params
        request_required_params
        request_more_params
        refresh_required_params
        refresh_more_params
    
        # Hashrefs
        authorization_default_params
        request_default_params
        refresh_default_params
    * Service provider collects arguments it wants

    In general, arguments passed into the constructor do not have to be passed into individual method calls. Furthermore in order to be able to do the automatic token refresh for you, the constructor must include the arguments that will be required.

    By default you are required to pass your client_id and client_secret. And optionally can pass a redirect_uri and scope. (The omission of state is a deliberate hint that if you use that field, you should be generating random values on the fly. And not trying to go to some reasonable default.)

    However what is required is up to the service provider.

    * LWP::Authen::OAuth2 overrides defaults from arguments

    The following defaults are available to be overridden in the constructor, or can be overridden later. In the unlikely event that there is a conflict with the service provider's arguments, these will have to be overridden later.

    error_handler => \&error_handler,

    Specifies the function that will be called when errors happen. The default is Carp::croak.

    is_strict => $bool,

    Is strict mode on? If it is, then excess parameters to requests that are part of the authorization process will trigger errors. If it is not, then excess arguments are passed to the service provider as is, who according to the specification is supposed to ignore them.

    Strict mode is the default.

    early_refresh_time => $seconds,

    How many seconds before the end of estimated access token expiration you will have should_refresh start returning true.

    prerefresh => \&prerefresh,

    A handler to be called before attempting to refresh tokens. It is passed the $oauth2 object. If it returns a token string, that will be used to generate tokens instead of going to the service provider.

    This hook is available in case you want logic to prevent multiple requests being sent at once to refresh tokens. By default this is missing.

    save_tokens => \&save_tokens,

    Whenever tokens are returned from the service provider, this callback will receive a token string that can be stored and then retrieved in another process that needs to construct a $oauth2 object.

    By default this is missing. However it is useful for many use cases.

    token_string => $token_string,

    Supply tokens generated in a previous request so that you don't have to ask the service provider for new ones. Some service providers refuse to hand out tokens too quickly, so this can be important.

    user_agent => $ua,

    What user agent gets used under the hood? Defaults to a new lWP::UserAgent created on the fly.

    * Sanity check

    Any arguments that are left over are assumed to be mistakes and a fatal warning is generated.

METHODS

Once you have an object, the following methods may be useful for writing a consumer.

$oauth2->authorization_url(%opts)

Generate a URL for the user to go to to request permissions. By default the response_type and client_id are defaulted, and all of redirect_uri, state and scope are optional but not required. However in practice this all varies by service provider and flow, so look for documentation on that for the actual list that you need.

$oauth2->request_tokens(%opts)

Request tokens from the service provider (if possible). By default the grant_type, client_id and client_secret are defaulted, and the scope is required. However in practice this all varies by service provider and flow, so look for documentation on that for the actual list that you need.

$oauth2->get(...)

Issue a get request to an OAuth 2 protected URL, just like you would using LWP::UserAgent to a normal URL.

$oauth2->head(...)

Issue a head request to an OAuth 2 protected URL, just like you would using LWP::UserAgent to a normal URL.

$oauth2->post(...)

Issue a post request to an OAuth 2 protected URL, just like you would using LWP::UserAgent to a normal URL.

$oauth2->delete(...)

Issue a delete request to an OAuth 2 protected URL, similar to the previous examples. (This shortcut is not by default available with LWP::UserAgent.)

$oauth2->put(...)

Issue a put request to an OAuth 2 protected URL, similar to the previous examples. (This shortcut is not by default available with LWP::UserAgent.)

$oauth2->request(...)

Issue any request that you could issue with LWP::UserAgent, except that it will be properly signed to go to an OAuth 2 protected URL.

$oauth2->should_refresh()

Is it time to refresh tokens?

$oauth2->set_early_refresh_time($seconds)

Set how many seconds before the end of token expiration the method should_refresh will start turning true. Values over half the initial expiration time of access tokens will be ignored to avoid refreshing too often. This defaults to 300.

$oauth2->set_is_strict($mode)

Set strict mode on/off. See the discussion of is_strict in the constructor for an explanation of what it does.

$oauth2->set_error_handler(\&error_handler)

Set the error handler. See the discussion of error_handler in the constructor for an explanation of what it does.

$oauth2->set_prerefresh(\&prerefresh)

Set the prerefresh handler. See the discussion of prerefresh_handler in the constructor for an explanation of what it does.

$oauth2->set_save_tokens($ua)

Set the save tokens handler. See the discussion of save_tokens in the constructor for an explanation of what it does.

$oauth2->set_user_agent($ua)

Set the user agent. This should respond to the same methods that a LWP::UserAgent responds to.

$oauth2->user_agent()

Get the user agent. The default if none was explicitly set is a new LWP::UserAgent object.

AUTHOR

Ben Tilly, <btilly at gmail.com>

BUGS

Please report any bugs or feature requests to bug-lwp-authen-oauth2 at rt.cpan.org, or through the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=LWP-Authen-OAuth2. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.

SUPPORT

You can find documentation for this module with the perldoc command.

    perldoc LWP::Authen::OAuth2

You can also look for information at:

ACKNOWLEDGEMENTS

Thanks to Rent.com for their generous support in letting me develop and release this module. My thanks also to Nick Wellnhofer <wellnhofer@aevum.de> for Net::Google::Analytics::OAuth2 which was very enlightening while I was trying to figure out the details of how to connect to Google with OAuth2.

LICENSE AND COPYRIGHT

Copyright 2013 Rent.com.

This program is free software; you can redistribute it and/or modify it under the terms of the the Artistic License (2.0). You may obtain a copy of the full license at:

http://www.perlfoundation.org/artistic_license_2_0

Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license.

If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license.

This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder.

This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed.

Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

3 POD Errors

The following errors were encountered while parsing the POD:

Around line 455:

Expected text after =item, not a bullet

Around line 470:

Expected text after =item, not a bullet

Around line 527:

Expected text after =item, not a bullet