Net::OAuth(3pm)

πŸ’– Net::OAuth πŸ’–

so bestie, you found the manual page for Net::OAuth β€” that's the Net::OAuth(3pm) page, living in the User Contributed Perl Documentation section. OAuth 1.0 for Perl, let's GO ✨


✨ NAME ✨

Net::OAuth β€” OAuth 1.0 for Perl πŸ’…


✨ SYNOPSIS ✨

okay so here's the whole vibe, top to bottom:

use Net::OAuth::Client;

# client_id is the Consumer Key, client_secret the Consumer Secret.
# Framework-agnostic: supply your own redirect and session handling.

my $client = Net::OAuth::Client->new(
    $client_id,
    $client_secret,
    site               => 'https://provider.example/',
    request_token_path => '/oauth/request_token',
    authorize_path     => '/oauth/authorize',
    access_token_path  => '/oauth/access_token',
    callback           => 'https://you.example/auth/callback',
    session            => \&session,
);

# 1. Send the user to the provider to authorize.
$client->authorize_url;

# 2. They return to your callback with oauth_token and oauth_verifier.
my $access_token = $client->get_access_token($token, $verifier);

# 3. Use the access token to fetch a protected resource.
my $response = $access_token->get('/profile');
die $response->status_line unless $response->is_success;
print $response->decoded_content;

like, ✨ three steps, that's the entire dance ✨


🚨 IMPORTANT 🚨

Net::OAuth gives you a low-level API for reading and writing OAuth messages. That's it. That's the whole job.

ngl, you probably wanna start with Net::OAuth::Client instead. πŸ’… fr fr, start there.


🌸 ABSTRACT 🌸

OAuth is, and I quote:

"An open protocol to allow secure API authentication in a simple and standard method from desktop and web applications."

In practical terms β€” and bestie this is the translation you actually need β€” OAuth is a mechanism for a Consumer to request protected resources from a Service Provider on behalf of a user. πŸ‘‘ main character energy, but the user is the main character.

pls go read the OAuth spec, it's right here: <http://oauth.net/documentation/spec> 🌈

Net::OAuth provides: ✨

  • classes that encapsulate OAuth messages (requests and responses). πŸ“¨
  • message signing ✍️
  • message serialization and parsing. πŸ”„
  • 2-legged requests (aka. tokenless requests, aka. consumer requests), see "CONSUMER REQUESTS" πŸ‘€

Net::OAuth does not provide: πŸ’€

  • Consumer or Service Provider encapsulation
  • token/nonce/key storage/management

so like, it hands you the message plumbing and nothing else. no cap. 🫢


πŸ’œ DESCRIPTION πŸ’œ

πŸ¦‹ OAUTH MESSAGES πŸ¦‹

An OAuth message is just a set of key-value pairs. iconic, honestly. The following message types are supported:

Requests πŸ“€

  • Request Token (Net::OAuth::RequestTokenRequest)
  • Access Token (Net::OAuth::AccessTokenRequest)
  • User Authentication (Net::OAuth::UserAuthRequest)
  • Protected Resource (Net::OAuth::ProtectedResourceRequest)
  • Consumer Request (Net::OAuth::ConsumerRequest) (2-legged / token-less request)

Responses πŸ“₯

  • Request Token (Net::OAuth::RequestTokenResponse)
  • Access Token (Net::OAuth:AccessTokenResponse)
  • User Authentication (Net::OAuth::UserAuthResponse)

Each OAuth message type has one or more required parameters, zero or more optional parameters, and most allow arbitrary parameters. flexible queen πŸ’…

All OAuth requests must be signed by the Consumer. Responses from the Service Provider, however, are not signed. that's just how it is bestie.

To create a message, the easiest way is to use the factory methods (Net::OAuth->request, Net::OAuth->response, Net::OAuth->message). The following method invocations are all equivalent:

$request = Net::OAuth->request('user authentication')->new(%params);
$request = Net::OAuth->request('user_auth')->new(%params);
$request = Net::OAuth->request('UserAuth')->new(%params);
$request = Net::OAuth->message('UserAuthRequest')->new(%params);

The more verbose way is to use the class directly:

use Net::OAuth::UserAuthRequest;
$request = Net::OAuth::UserAuthRequest->new(%params);

You can also create a message by deserializing it from a Authorization header, URL, query hash, or POST body 🀯

$request = Net::OAuth->request('protected resource')->from_authorization_header($ENV{HTTP_AUTHORIZATION}, %api_params);
$request = Net::OAuth->request('protected resource')->from_url($url, %api_params);
$request = Net::OAuth->request('protected resource')->from_hash({$q->Vars}, %api_params); # CGI
$request = Net::OAuth->request('protected resource')->from_hash($c->request->params, %api_params); # Catalyst
$response = Net::OAuth->response('request token')->from_post_body($response_content, %api_params);
heads up bestie πŸ‘€ β€” the deserialization methods (as opposed to new()) expect OAuth protocol parameters to be prefixed with 'oauth_', exactly like you'd expect in a valid OAuth message. don't forget the prefix, it's giving "bug report at 2am".

Before sending a request, the Consumer must first sign it:

$request->sign;

When receiving a request, the Service Provider should first verify the signature, and should say which signature methods it is willing to accept:

$request = Net::OAuth->request('protected resource')->from_authorization_header(
    $ENV{HTTP_AUTHORIZATION},
    %api_params,
    allowed_signature_methods => [qw/HMAC-SHA1 HMAC-SHA256/],
);
die "Signature verification failed" unless $request->verify;

See "VERIFYING MESSAGES" for why the second part matters. πŸ‘‡ (spoiler: it matters A LOT)

πŸ” VERIFYING MESSAGES πŸ”

oauth_signature_method is a message parameter: it is chosen by whoever sent the message, and on the receiving side it arrives from the network along with the signature it describes. verify dispatches on it, so without an allowed_signature_methods list the sender is choosing which algorithm β€” and therefore which key β€” the receiver checks their signature with.

That is a real problem for a Service Provider deployed with RSA-SHA1, because it holds only the Consumer's public key. An attacker who sends oauth_signature_method=HMAC-SHA1 instead moves verification onto the symmetric path, whose key signature_key in Net::OAuth::Request derives from consumer_secret and token_secret β€” fields RSA-SHA1 does not use and which such a deployment has no reason to keep secret. 😭 The equivalent downgrade between two symmetric methods (HMAC-SHA256 to HMAC-SHA1, or to PLAINTEXT) is weaker but is the same mechanism.

Pass allowed_signature_methods as an API parameter to any message you are going to verify:

allowed_signature_methods => [qw/RSA-SHA1/]

verify croaks if the message names anything else. πŸ’€ Deployments that cannot reach every call site β€” because verification happens inside a framework or a wrapper module β€” can set the process-wide default instead:

@Net::OAuth::ALLOWED_SIGNATURE_METHODS = qw/RSA-SHA1/;

An allowed_signature_methods on the message overrides that default. πŸ‘‘

If neither is set, verify croaks. There is no method it could safely assume on your behalf: only you know which one your Consumers registered with, and taking the answer from the message is the problem this list exists to solve. periodt.

Signing is not affected: a Consumer choosing the method for a message it is about to send is choosing for itself, not on someone else's behalf. ✨

🧚 Upgrading 🧚

This is a breaking change. Before this release verify took the algorithm from the message; every existing caller is therefore unpinned, and will croak until it says what it accepts. 😬 The migration is one parameter per verifying call site, or one package variable per process, naming the method your Consumers already use β€” for the great majority of deployments:

@Net::OAuth::ALLOWED_SIGNATURE_METHODS = qw/HMAC-SHA1/;

The break is deliberate: a warning would have left every deployment that does not read release notes verifying with an attacker-chosen algorithm. yes queen, break it on purpose, that's the responsible slay πŸ’…

When sending a message the last step is to serialize it and send it to wherever it needs to go. The following serialization methods are available:

$response->to_post_body # a application/x-www-form-urlencoded POST body

$request->to_url # the query string of a URL

$request->to_authorization_header # the value of an HTTP Authorization header

$request->to_hash # a hash that could be used for some other serialization

πŸŽ€ API PARAMETERS vs MESSAGE PARAMETERS πŸŽ€

Net::OAuth defines 'message parameters' as parameters that are part of the transmitted OAuth message. These include any protocol parameter (prefixed with 'oauth_' in the message), and any additional message parameters (the extra_params hash).

'API parameters' are parameters required to build a message object that are not transmitted with the message, e.g. consumer_secret, token_secret, request_url, request_method. so like: message params = shipped out into the world, API params = stay home, do the work.

There are various methods to inspect a message class to see what parameters are defined:

$request->required_message_params;
$request->optional_message_params;
$request->all_message_params;
$request->required_api_params;
$request->optional_api_params;
$request->all_api_params;
$request->all_params;

E.g.

use Net::OAuth;
use Data::Dumper;
print Dumper(Net::OAuth->request("protected resource")->required_message_params);

$VAR1 = [
         'consumer_key',
         'signature_method',
         'timestamp',
         'nonce',
         'token'
       ];

🫢 ACCESSING PARAMETERS 🫢

All parameters can be get/set using accessor methods. E.g.

my $consumer_key = $request->consumer_key;
$request->request_method('POST');

so simple. so clean. we love to see it. πŸ’–

🌈 THE REQUEST_URL PARAMETER 🌈

Any query parameters in the request_url are removed and added to the extra_params hash when generating the signature. βœ‚οΈ

E.g. the following requests are pretty much equivalent:

my $request = Net::OAuth->request('Request Token')->new(
 %params,
 request_url => 'https://photos.example.net/request_token',
 extra_params => {
  foo => 'bar'
 },
);

my $request = Net::OAuth->request('Request Token')->new(
 %params,
 request_url => 'https://photos.example.net/request_token?foo=bar',
);

Calling $request->request_url will still return whatever you set it to originally. If you want to get the request_url with the query parameters removed, you can do:

my $url = $request->normalized_request_url;

same energy, two outfits, iykyk πŸ’…

πŸ‘‘ SIGNATURE METHODS πŸ‘‘

The following signature methods are supported:

  • PLAINTEXT
  • HMAC-SHA1
  • HMAC-SHA256
  • RSA-SHA1

The signature method is determined by the value of the signature_method parameter that is passed to the message constructor.

If an unknown signature method is specified, the signing/verification will throw an exception. 🚨

πŸ“ PLAINTEXT SIGNATURES πŸ“

This method is a trivial signature which adds no security. Not recommended. like bestie, it's giving "lock on a paper gate" 😭

⭐ HMAC-SHA1 SIGNATURES ⭐

This method is available if you have Digest::SHA installed. This is by far the most commonly used method. πŸ‘‘

🌸 HMAC-SHA256 SIGNATURES 🌸

This method is available if you have Digest::SHA installed. (same gatekeeping, same install 🫢)

πŸ’œ RSA-SHA1 SIGNATURES πŸ’œ

To use RSA-SHA1 signatures, pass in a Crypt::OpenSSL::RSA object (or any object that can do $o->sign($str) and/or $o->verify($str, $sig)) πŸ”₯

E.g.

Consumer:

        use Crypt::OpenSSL::RSA;
        use File::Slurp;
        $keystring = read_file('private_key.pem');
        $private_key = Crypt::OpenSSL::RSA->new_private_key($keystring);
        $request = Net::OAuth->request('request token')->new(%params);
        $request->sign($private_key);

Service Provider:

        use Crypt::OpenSSL::RSA;
        use File::Slurp;
        $keystring = read_file('public_key.pem');
        $public_key = Crypt::OpenSSL::RSA->new_public_key($keystring);
        $request = Net::OAuth->request('request token')->new(
            %params,
            allowed_signature_methods => ['RSA-SHA1'],
        );
        if (!$request->verify($public_key)) {
               die "Signature verification failed";
        }

A Service Provider deployed this way holds only the Consumer's public key, so it is the deployment with the most to lose from letting the message choose the algorithm: without allowed_signature_methods a request naming HMAC-SHA1 would be checked against consumer_secret, which RSA-SHA1 does not use and such a deployment has no reason to keep secret. See "VERIFYING MESSAGES".

πŸ’€ bestie, this is one of those genuinely important security bits. If you're an SP holding only a public key, pin your algorithms. Do not let the message pick for you. Periodt.

Note that you can pass the key in as a parameter called 'signature_key' to the message constructor, rather than passing it to the sign/verify method, if you like. convenient! πŸ’…


πŸ›οΈ CONSUMER REQUESTS

To send a request without including a token, use a Consumer Request:

    my $request = Net::OAuth->request('consumer')->new(
            consumer_key => 'dpf43f3p2l4k3l03',
            consumer_secret => 'kd94hf93k423kf44',
            request_url => 'http://provider.example.net/profile',
            request_method => 'GET',
            signature_method => 'HMAC-SHA1',
            timestamp => '1191242096',
            nonce => 'kllo9940pd9333jh',
    );

    $request->sign;

See Net::OAuth::ConsumerRequest


🌍 I18N ✨

Per the OAuth spec, when making the signature Net::OAuth first encodes parameters to UTF-8. This means that any parameters you pass to Net::OAuth, if they might be outside of ASCII character set, should be run through Encode::decode() (or an equivalent PerlIO layer) first to decode them to Perl's internal character structure.

πŸ¦‹ tl;dr: decode your strings to Perl's internal characters before handing them over, or the signature vibes will not be correct. #iykyk

πŸ’« OAUTH 1.0A πŸ‘‘

Background:

Net::OAuth defaults to OAuth 1.0 spec compliance, and supports OAuth 1.0 Rev A with an optional switch:

use Net::OAuth
$Net::OAuth::PROTOCOL_VERSION = Net::OAuth::PROTOCOL_VERSION_1_0A;

It is recommended that any new projects use this switch if possible, and existing projects move to supporting this switch as soon as possible. Probably the easiest way for existing projects to do this is to turn on the switch and run your test suite. The Net::OAuth constructor will throw an exception where the new protocol parameters (callback, callback_confirmed, verifier) are missing.

Internally, the Net::OAuth::Message constructor checks $Net::OAuth::PROTOCOL_VERSION and attempts to load the equivalent subclass in the Net::OAuth::V1_0A:: namespace. So if you instantiate a Net::OAuth::RequestTokenRequest object, you will end up with a Net::OAuth::V1_0A::RequestTokenRequest (a subclass of Net::OAuth::RequestTokenRequest) if the protocol version is set to PROTOCOL_VERSION_1_0A. You can also select a 1.0a subclass on a per-message basis by passing

    protocol_version => Net::OAuth::PROTOCOL_VERSION_1_0A

in the API parameters hash.

If you are not sure whether the entity you are communicating with is 1.0A compliant, you can try instantiating a 1.0A message first and then fall back to 1.0 if that fails:

    use Net::OAuth
    $Net::OAuth::PROTOCOL_VERSION = Net::OAuth::PROTOCOL_VERSION_1_0A;
    my $is_oauth_1_0 = 0;
    my $response = eval{Net::OAuth->response('request token')->from_post_body($res->content)};
    if ($@) {
        if ($@ =~ /Missing required parameter 'callback_confirmed'/) {
            # fall back to OAuth 1.0
            $response = Net::OAuth->response('request token')->from_post_body(
                $res->content,
                protocol_version => Net::OAuth::PROTOCOL_VERSION_1_0
            );
            $is_oauth_1_0 = 1; # from now on treat the server as OAuth 1.0 compliant
        }
        else {
            die $@;
        }
    }

At some point in the future, Net::OAuth will default to Net::OAuth::PROTOCOL_VERSION_1_0A.

🧚 future-you is gonna wake up one day and the default will have changed. plan accordingly bestie.

πŸ‘€ SEE ALSO 🌈

Check out Net::OAuth::Simple β€” it has a simpler API that may be more to your liking

Check out Net::Twitter::OAuth for a Twitter-specific OAuth API

Check out WWW::Netflix::API for a Netflix-specific OAuth API


πŸ“ TODO πŸ’…

  • Support for repeating/multivalued parameters
  • Add convenience methods for SPs

Something like:

  # direct from CGI.pm object
  $request = Net::OAuth->request('Request Token')->from_cgi_query($cgi, %api_params);

  # direct from Catalyst::Request object
  $request = Net::OAuth->request('Request Token')->from_catalyst_request($c->req, %api_params);

  # from Auth header and GET and POST params in one
  local $/;
  my $post_body = <STDIN>;
  $request = Net::OAuth->request('Request Token')->from_auth_get_and_post(
      $ENV{HTTP_AUTHORIZATION},
      $ENV{QUERY_STRING},
      $post_body,
      %api_params
  );

πŸ’– AUTHOR 🫢

Originally by Keith Grennan <foss@nearlyfree.org>

Currently maintained by Robert Rothenberg <perl@rhizomnic.com>


🌸 CONTRIBUTORS

  • Adam Taylor
  • Brad Whitaker
  • Cosimo Streppone <cosimo@cpan.org>
  • Daisuke Maki
  • Gregor Herrmann
  • James Raspass <jraspass@gmail.com>
  • Jeff Dairiki
  • Jens Rehsack
  • Katou Akira
  • Masayoshi Sekimura
  • Marc Mims
  • Mike Schleif
  • Nobuo Danjou
  • Pattawan Gerlings-Kaewduangdee (oiami)
  • Sergey Romanov <sromanov-dev@yandex.ru>
  • Shawn Moore <cpan@sartak.org>
  • Simon Wistow
  • TomaΕΎ Ε olc <avian@cpan.org>

Copyright 2007-2012, 2024-2026 Keith Grennan

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


and that's a wrap, bestie!! ✨ this little masterpiece is Net::OAuth(3pm), churned out by perl v5.42.3 on 2026-08-19. go forth and sign your messages, and remember β€” decode your UTF-8, pin your signature methods, and slay πŸ’–πŸŽ€πŸ¦‹

πŸ“¦ where this page comes from