7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PowerShellでGoogle APIに使うOAuth 2.0トークンを取得する

Last updated at Posted at 2015-07-28

Google OAuth2.0のリフレッシュトークンには有効期限がない。
どの認証フローであってもリフレッシュトークンを取得できればアクセストークンを取得できる。

参考: Using OAuth 2.0 to Access Google APIs

デバイス認証フローでトークンを取得する。

コンソールで認証フローを開始する
verification_urluser_codeを取得する。

ブラウザでverification_urlにアクセスする。
許可リクエストを承認してuser_codeを入力する。

コンソールでdevice_codeを指定してトークンを取得する。

$client_id = ""
$client_secret = ""
$scope = ""

$data = Invoke-RestMethod `
    -Uri 'https://accounts.google.com/o/oauth2/device/code' `
    -Method Post `
    -ContentType "application/x-www-form-urlencoded" `
    -Body @{
        client_id=$client_id;
        scope=$scope
    }

$data.user_code

# ブラウザを起動
start $data.verification_url

do
{

  Read-Host '?'

  $result = Invoke-RestMethod `
      -Uri "https://accounts.google.com/o/oauth2/token" `
      -Method Post `
      -ContentType "application/x-www-form-urlencoded" `
      -Body @{
          client_id = $client_id;
          client_secret = $client_secret ;
          code=$data.device_code;
          grant_type='http://oauth.net/grant_type/device/1.0';
      }

  $result

} while($result.error)

# 結果
$result.access_token
$result.refresh_token
$result.expires_in
$result.token_type
$result

7
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?