LWP::A...:OAuth2(3pm)

πŸ“¦
version 0.20 Β· 2 versions
  • 0.20 Β· debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking (latest)
  • 0.18 Β· ubuntu jammy
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

πŸ’– LWP::Authen::OAuth2 β€” the manual page, bestie edition πŸ’–

okay so you're reading the docs for LWP::Authen::OAuth2 (that's the LWP::A...:OAuth2(3pm) page, from the User Contributed Perl Documentation corner of the universe). Buckle up, we're gonna make OAuth2 make sense. πŸŽ€


✨ NAME ✨

LWP::Authen::OAuth2</purl> β€” Make requests to OAuth2 APIs.


🌸 VERSION 🌸

version 0.20


πŸ¦‹ SYNOPSIS πŸ¦‹

Okay so picture this: OAuth 2 is a protocol that lets 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. That's the whole vibe. And this module? It tries to make life easier for someone who wants to write a consumer in Perl. 🫢

More specifically β€” and this is the good part β€” it gives you convenience methods for all of the requests that get made to the service provider as part of the permission handshake. And after that? It proxies off of LWP::UserAgent so you can send properly authenticated requests to the API you're trying to use. And when possible, it'll include transparent refresh/retry logic for access tokens expiring. iconic behavior, honestly. ✨

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

Quick heads up bestie: this module will not help with OAuth 1. Nope. Different era. See the similarly named but completely unrelated LWP::Authen::OAuth for a module that can help with that one. πŸ™ˆ


πŸ‘‘ Service providers that come ready-to-use πŸ‘‘

Currently LWP::Authen::OAuth2 provides ready-to-use classes to use OAuth2 with:


And the tea is: you can also access any other OAuth2 service by setting up a plain LWP::Authen::OAuth2 object. If you do that, and the service provider might be of interest to other people, please submit a patch so we can include it in this distribution, or release it as a standalone package. be the change you want to see in the CPAN πŸ’…


πŸ’… Examples of simple usage πŸ’…

Here's the group-chat-approved walkthrough, bestie:

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,
                 save_tokens_args => [ $dbh ],

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

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

# The authorization_url sends the user to the service provider to
# say that you want to be authorized.  After the user confirms that
# request, the service provider sends the user back to you with a
# code.  This might be a CGI parameter, something that the user is
# supposed to paste to you - that's between you and the service
# provider.

# Assuming that you have your code, 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 have a save_tokens callback, that gets passed this string
# whenever the tokens change.
#
# This string bears a suspicious resemblance to serialized JSON.
my $token_string = $oauth2->token_string,

# Access the API.  Consult the service_provider's documentation for when
# to use which type of request.  Note that argument processing is the
# same as in LWP.  Thus the parameters array and headers hash are both
# optional.
$oauth2->get($url, %header);
$oauth2->post($url, \@parameters, %header);
$oauth2->put($url, %header);
$oauth2->delete($url, %header);
$oauth2->head($url, %header);

# And if you need more flexibility, you can use LWP::UserAgent's request
# method
$oauth2->request($http_request, $content_file);

# In some flows you can refresh tokens, in others you have to go through
# the handshake yourself.  This method lets you know whether a refresh
# looks possible.
$oauth2->can_refresh_tokens();

# This method lets you know when it is time to reauthorize so that you
# can find out in a nicer way than failing an API call.
$oauth2->should_refresh();

And that's the synopsis, bestie β€” more sections coming right up, don't go anywhere πŸ¦‹βœ¨

✨ CONSTRUCTOR ✨

okay bestie, so when you call LWP::Authen::OAuth2->new(...), all those arguments come in as a key/value list. Key/value list, like a little grocery list of vibes. And they get processed in these phases, in this exact order:

  • Construct service provider
  • Service provider collects arguments it wants
  • LWP::Authen::OAuth2 overrides defaults from arguments
  • Sanity check

and now let's get into each one, because the details matter, periodt.

πŸ’… Construct service provider

there are literally two ways to construct a service provider. two. pick your fighter.

🌸 Prebuilt class

to load a prebuilt class you only need one or two arguments. so chill.

  • service_provider => $Foo, β€” in this construct, $Foo is the base class for your service provider. the actual class will be the first of the following two classes that can be loaded. if neither can be found? that's an error, sorry bestie:
LWP::Authen::OAuth2::ServiceProvider $Foo
$Foo

a whole list of prebuilt service provider classes lives in LWP::Authen::OAuth2::ServiceProvider, plus instructions for making a new one. go look, iykyk.

  • client_type => $name_of_client_type β€” some service providers keep track of your client type (like a "webserver" application, an "installed" application, etc.) and they'll treat them differently. a base service provider class can choose to accept a client_type parameter so it knows what to expect.
whether that happens at all, and which values are allowed, is entirely up to the service provider class. not our call, bestie. πŸ™ˆ

πŸ¦‹ Built on the fly

the behavior of simple service providers can just be described on the fly, no prebuilt class required. iconic. to do that, these arguments can be filled in from your service provider:

  • authorization_endpoint => $auth_url, β€” this is the URL the user gets directed to in the authorization request.
  • token_endpoint => $token_url, β€” this is the URL the consumer goes to for tokens.

✨ Various optional fields

LWP::Authen::OAuth2::ServiceProvider documents a ton of methods that are available to customize the actual requests being made, plus the defaults available. simple service providers can probably get by without any of this, but here's the list of those methods you can specify in the constructor instead:

# Arrayrefs
required_init
optional_init
authorization_required_params
authorization_optional_params
request_required_params
request_optional_params
refresh_required_params
refresh_optional_params

# Hashrefs
authorization_default_params
request_default_params
refresh_default_params

πŸŽ€ Service provider collects arguments it wants

ngl, generally the arguments you pass into the constructor do not have to be passed into individual method calls. and on top of that, to be able to do the automatic token refresh for you, the constructor has to include the arguments that will be required.

by default you're required to pass your client_id and client_secret. and optionally you can pass a redirect_uri and scope. (the omission of state is a deliberate hint, bestie β€” if you use that field, you should be generating random values on the fly. do not try to go to some reasonable default. that's the whole point.) πŸ’€

but yeah, what's actually 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 they can be overridden later. in the unlikely event there's a conflict with the service provider's arguments, you'll have to override them later. sorry, that's just how it is.

  • error_handler => \&error_handler, β€” specifies the function that gets 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's not, then excess arguments get passed to the service provider as-is, and according to the specification the service provider is supposed to ignore them.

strict mode is the default.

  • early_refresh_time => $seconds, β€” how many seconds before the end of the estimated access token expiration you'll have should_refresh start returning true.
  • prerefresh => \&prerefresh, β€” a handler to be called before attempting to refresh tokens. it's passed the $oauth2 object. if it returns a token string, that gets used to generate tokens instead of going to the service provider.

the purpose of this hook is so that even if you have multiple processes accessing an API simultaneously, only one of them will try to refresh tokens with the service provider. (service providers may dislike having multiple refresh requests arrive at once from the same consumer for the same user. rude of them but okay.)

by default this is not provided.

  • save_tokens => \&save_tokens, β€” whenever tokens are returned from the service provider, this callback receives a token string that can be stored and then retrieved in another process that needs to construct a $oauth2 object.

by default this is not provided. however, if you intend to access the API multiple times from multiple processes, it is recommended.

  • save_tokens_args => [ args ], β€” additional arguments passed to the save_tokens callback function after the token string. this can be used to pass things like database handles or other data to the callback along with the token string. provide a reference to an array of arguments in the constructor. when the callback is called the arguments are passed to the callback as an array, so in the example below $arg1 will be "foo" and $arg2 will be "bar".
...
save_tokens => \&save_tokens,
save_tokens_args => [ "foo", "bar" ],
...

sub save_tokens {
    my ($token_string, $arg1, $arg2) = @_;

    ...
}
  • token_string => $token_string, β€” supply tokens generated in a previous request so 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 lowkey 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. so don't leave strays lying around, bestie. clean up your args. πŸ’…

✨ METHODS ✨

okay bestie, you've got your object, now here's the whole toolbox 🧰 β€” everything you can actually do with it once it exists. These are the methods that'll be useful when you're writing a consumer. go off πŸ’…


πŸ’– $oauth2->authorization_url(%opts)

Makes you a URL that you send the user to, so they can go request permissions. πŸŽ€

By default, response_type and client_id are defaulted, and all of redirect_uri, state and scope are optional but not required. (yes bestie, "optional but not required" is what the docs say, and we're keeping it exactly like that, no notes 😭)

But lowkey, in practice this all varies by service provider and client type β€” so go look at the documentation for that to find the actual list you need. no cap, every provider does its own thing.


πŸ’– $oauth2->request_tokens(%opts)

Requests tokens from the service provider (if possible). πŸ¦‹

By default the grant_type, client_id and client_secret are defaulted, and the scope is required.

But again β€” in practice this all varies by service provider and client type, so check the docs for the provider you're talking to for the actual list you need. it's giving "everyone made up their own rules" fr fr πŸ™ˆ


πŸ’– $oauth2->get(...)

Issues a get request to an OAuth 2 protected URL, just like you'd do using LWP::UserAgent to a normal URL. iconic behavior honestly ⭐


πŸ’– $oauth2->head(...)

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


πŸ’– $oauth2->post(...)

Issues a post request to an OAuth 2 protected URL, just like you would using LWP::UserAgent to a normal URL. πŸ’œ


πŸ’– $oauth2->delete(...)

Issues a delete request to an OAuth 2 protected URL, similar to the previous examples. πŸ“

heads up bestie: this shortcut is not by default available with LWP::UserAgent. so we're kind of spoiling you here πŸ’…

πŸ’– $oauth2->put(...)

Issues a put request to an OAuth 2 protected URL, similar to the previous examples. 🌸

same vibe check as above: this shortcut is not by default available with LWP::UserAgent either.

πŸ’– $oauth2->request(...)

Issues any request that you could issue with LWP::UserAgent β€” except it'll be properly signed to go to an OAuth 2 protected URL. so you get all the flexibility, none of the signature drama ✨


πŸ’– $oauth2->make_api_call($uri, $params, $headers)

This one's a convenience method, and bestie, it's a gift. 🎁 It makes a call to an OAuth2 API endpoint given by $uri, and returns the JSON response decoded to a hash.

  • If the $params hashref arg is set, its contents get JSON encoded and sent as POST request content.
  • Otherwise it makes a GET request.
  • Optional $headers may be sent, and they'll be passed through to $oauth->get() or $oauth->post().

If the call succeeds, it returns the response's JSON content decoded as a hash β€” or, if no response body was returned, a value of 1 to indicate success. πŸŽ‰

On failure it returns undef, and the error message is available from $oauth2->api_call_error(). 😭


πŸ’– $oauth2->api_call_error()

If an error happened in $oauth2->make_api_call(), this method returns it. The error message comes from HTTP::Response->error_as_HTML(). so yeah, you get actual HTML error text back, fun little quirk 🫢


πŸ’– $oauth2->api_url_base()

Returns the base URL of the service provider β€” sometimes useful to be used in the content of OAuth2 API calls. πŸ’«


πŸ’– $oauth2->can_refresh_tokens

Is sufficient information available to try to refresh tokens? that's the whole question. πŸ€”


πŸ’– $oauth2->should_refresh()

Is it time to refresh tokens? ⏰


πŸ’– $oauth2->set_early_refresh_time($seconds)

Sets how many seconds before the end of token expiration the method should_refresh will start turning true.

real talk: values over half the initial expiration time of access tokens will be ignored, so you don't refresh too often. this defaults to 300. πŸ‘‘

πŸ’– $oauth2->expires_time()

Returns the raw epoch expiration time of the current access token. typically this is 3600 seconds greater than the time of token creation. πŸ•


πŸ’– $oauth2->set_is_strict($mode)

Sets strict mode on/off. see the discussion of is_strict in the constructor for what it actually does β€” we already covered that, go peek back up there bestie πŸ’…


πŸ’– $oauth2->set_error_handler(\&error_handler)

Sets the error handler. see the discussion of error_handler in the constructor for an explanation of what it does. πŸ› οΈ


πŸ’– $oauth2->set_prerefresh(\&prerefresh)

Sets the prerefresh handler. see the discussion of prerefresh_handler in the constructor for an explanation of what it does. πŸ”„


πŸ’– $oauth2->set_save_tokens($ua)

Sets 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)

Sets the user agent. this should respond to the same methods that a LWP::UserAgent responds to. πŸ€–


πŸ’– $oauth2->user_agent()

Gets the user agent. the default, if none was explicitly set, is a new LWP::UserAgent object. so you always have something there, slay 🌈


🌟 Contributors


🫢 ACKNOWLEDGEMENTS 🫢

Thanks to Rent.com <http://www.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. that's the origin story fr fr πŸ’–

Thanks to:


πŸ‘‘ AUTHORS πŸ‘‘

  • Ben Tilly, <btilly at gmail.com>
  • Thomas Klausner <domm@plix.at>

This software is copyright (c) 2013 - 2022 by Ben Tilly, Rent.com, Thomas Klausner.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. πŸͺ✨


and that's a wrap bestie!! πŸŽ‰ this whole thing came from perl v5.36.0 and it's dated 2023-02-04 β€” go forth and OAuth responsibly, mwah πŸ’…πŸ’–

πŸ“¦ where this page comes from