Last active
January 5, 2016 14:16
-
-
Save jkramer/087732a66c256fa4fca3 to your computer and use it in GitHub Desktop.
Two-legged OAuth for Mojo::UserAgent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package Mojo::UserAgent::OAuth; | |
| use Mojo::Base -base; | |
| use Mojo::URL; | |
| use Net::OAuth; | |
| our $VERSION = 0.01; | |
| has [qw( consumer_key consumer_secret )]; | |
| has signature_method => 'HMAC-SHA1'; | |
| sub sign_callback { | |
| my ($self) = @_; | |
| return 'start' => sub { | |
| my ($ua, $tx) = @_; | |
| $self->sign_request($tx->req); | |
| }; | |
| } | |
| sub sign_request { | |
| my ($self, $req) = @_; | |
| my $request_url = $req->url->clone; | |
| my $query = $req->url->query; | |
| $request_url->query(Mojo::Parameters->new); | |
| my $oauth = Net::OAuth->request('consumer')->new( | |
| consumer_key => $self->consumer_key, | |
| consumer_secret => $self->consumer_secret, | |
| request_url => $request_url->to_string, | |
| request_method => $req->method, | |
| signature_method => $self->signature_method, | |
| timestamp => time, | |
| nonce => $self->nonce, | |
| extra_params => $query->to_hash, | |
| ); | |
| $oauth->sign; | |
| $req->headers->add(Authorization => $oauth->to_authorization_header); | |
| } | |
| sub nonce { | |
| my @a = ('A'..'Z', 'a'..'z', 0..9); | |
| join('', map { $a[rand(scalar(@a))] } (0..31)); | |
| } | |
| 1 | |
| __END__ | |
| use Mojo::UserAgent; | |
| use Mojo::UserAgent::OAuth; | |
| my $ua = Mojo::UserAgent->new; | |
| my $oauth = Mojo::UserAgent::OAuth->new( | |
| consumer_key => 'my-key', | |
| consumer_secret => 'my-secret', | |
| ); | |
| # Sign all requests from this UA instance: | |
| $ua->on($oauth->sign_callback); | |
| $ua->get(...) | |
| # Sign single request: | |
| $ua->once($oauth->sign_callback); | |
| $ua->get(...) | |
| # Chained: | |
| say $ua->tap(once => $oauth->sign_callback)->get(...)->res->body; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment