0

我在 perl 中使用我的应用程序进行 oauth 身份验证时遇到了这个问题:

401 Unauthorized 验证 oauth 签名和令牌失败

这是我的代码:

sub Twitter {

my $IN = new CGI;

  my $qs = build_query({
    oauth_callback => $callback_url,
    oauth_consumer_key => $consumer_key,
    oauth_nonce => time,
    oauth_signature_method => "HMAC-SHA1",
    oauth_timestamp => time,
    oauth_version => "1.0"
  });

# Create Signature

  my $signing_key = $IN->escape($consumer_secret)."&";

  my $base_signature = "POST&".$IN->escape($request_token_url)."&".$qs;

  use Digest::HMAC_SHA1;

  my $hmac = Digest::HMAC_SHA1->new($signing_key);
  $hmac->add($base_signature);

  $qs .= "&oauth_signature=".$IN->escape($hmac->b64digest);

# Fetch the page

  use LWP;
  my $ua = LWP::UserAgent->new;
  my $req = HTTP::Request->new(POST => $request_token_url);
  $req->content_type('application/x-www-form-urlencoded');
  $req->content($qs);

  my $res = $ua->request($req);

# Check the outcome of the response
  unless ($res->is_success) {
    print $IN->header.$res->status_line, "\n";
    print $res->content;
    exit;
  }
  print $IN->header.$res->content;
}
sub build_query {
  my $input = shift;
  use URI;
  my $uri = URI->new;
  $uri->query_form($input);
  return $uri->query;
}

我显然已经删除了我的回调 url 和关键信息。

4

1 回答 1

1

我想到了。我对签名进行了错误的编码,我必须对查询字符串进行排序,并且在这种情况下不需要回调 URL。这是我的工作代码:

sub Twitter {

  my $IN = new CGI;

  my $params = {
    oauth_consumer_key => $consumer_key,
    oauth_nonce => time,
    oauth_signature_method => "HMAC-SHA1",
    oauth_timestamp => time,
    oauth_version => "1.0"
  };
  my $qs = build_sorted_query($params);

  my $signing_key = $IN->escape($consumer_secret)."&";

  my $signature_base = "POST&".$IN->escape($request_token_url)."&".$IN->escape($qs);

  use Digest::HMAC_SHA1;
  use MIME::Base64;

  my $hmac = Digest::HMAC_SHA1->new($signing_key);
  $hmac->add($signature_base);

  $params->{oauth_signature} = $IN->escape(encode_base64($hmac->digest));

  $qs = build_sorted_query($params);

  use LWP;
  my $ua = LWP::UserAgent->new;
  my $req = HTTP::Request->new(POST => $request_token_url);
  $req->content_type('application/x-www-form-urlencoded');
  $req->content($qs);

  my $res = $ua->request($req);

# Check the outcome of the response
  unless ($res->is_success) {
    print $IN->header.$res->status_line, "\n";
    print $res->content;
    exit;
  }
  print $IN->header.$res->content;
  return;
}
sub build_sorted_query {
  my $input = shift;
  my $qs;
  foreach (sort keys %$input) {
      $qs .= $_."=".$input->{$_}."&";
  }
  return substr ($qs, 0, -1);
}

感谢您的关注!

于 2013-09-10T21:54:33.180 回答