忍者ブログ

ひつ(じのひよこが)プログラミングします。
お仕事や趣味で困ったこととか、何度も「あれ?どうだったかしら」と調べたりしたこととか、作ったものとか、こどものこととかを書きます
★前は週末定期更新でしたが今は不定期更新です

2024/04    03« 1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  »05

perl で OAuth2 の token を取ったりする

use strict;
use LWP::UserAgent;
use JSON::PP;

my $browser = LWP::UserAgent->new;
my $json = JSON::PP->new;

sub getAccessToken {  
  my $code = $_[0];
  my $redirect_url = $_[1];
  my $oauth_scope = $_[2];
  my $oauth_client_id = $_[3];
  my $oauth_secret_id = $_[4];
  my $token_url = "https://accounts.google.com/o/oauth2/token";

  my $token_request = HTTP::Request->new(POST => $token_url);
  $token_request->content_type('application/x-www-form-urlencoded');
  my $body = "redirect_uri=$oauth_redirect_url&scope=$oauth_scope&client_id=$oauth_client_id&client_secret=$oauth_secret_id&grant_type=authorization_code&code=$code";
  $token_request->content($body);
  my $token_response = $browser->request($token_request);
  my @rawResult = decode_json $token_response->content;
  my $token = $rawResult[0]->{'access_token'};
  return $token;
}

print getAccessToken(
  "nankanankaNankaRondomeNaCodeCode9877",
  "http%3A%2F%2Fsheeprogramming.iku4.com%2F",
  "https://www.googleapis.com/auth/userinfo.profile%20email",
  "5348789543906-o86eefe6g7clf855htsefii06cin.apps.googleusercontent.com",
  "ran51Random25"
);

こんな感じでアクセストークンが取得できた。今後なんか使いそうなのでメモ。

PR

コメント

ただいまコメントを受けつけておりません。

ブログ内検索

P R