LoginSignup
5
4

More than 1 year has passed since last update.

LINE WORKS API 2.0 を PowerShell で叩いてみる (その1 : JWT の処理)

Last updated at Posted at 2022-05-18

先日 LINE WORKS API 2.0 がリリースされましたので、早速使ってみます。

LINE WORKS API を利用する際には、JWT でアクセストークンを取得しますが、ドキュメントを見ても PowerShell から利用するのはちょっと難しいですよね。
PowerShell で JWT を取り扱うには、powershell-jwtが便利です。

powershell-jwt を利用して、LINE WORKS API を利用するための Token を取得し、取得した Token を埋め込んだ Header オブジェクトを生成してみましょう。

$PrivKeyPath = '.\private_202212345678.key'
$ClientId = 'bJLxxxxxxxx'
$ClientSecret = '8Adxxxx'
$SvcAccount = 'xxxxx.serviceaccount@yourgroupname'
$Scope = 'user,bot,orgunit'

Import-Module powershell-jwt

$rsaPrivateKey = Get-Content $PrivKeyPath -AsByteStream

$iat = [int](Get-Date -UFormat %s)
$exp = $iat + 3600

$payload = @{
    sub = $SvcAccount
    iat = $iat
}
    
$jwt = New-JWT -Algorithm 'RS256' -SecretKey $rsaPrivateKey -PayloadClaims $payload -ExpiryTimestamp $exp -Issuer $ClientId
    
$requestHeader = @{
    'Content-Type' = 'application/x-www-form-urlencoded'
}

$requestBody = @{
    assertion     = $jwt
    grant_type    = 'urn:ietf:params:oauth:grant-type:jwt-bearer'
    client_id     = $ClientId
    client_secret = $ClientSecret
    scope         = $Scope
}

$url = 'https://auth.worksmobile.com/oauth2/v2.0/token'
$response = Invoke-RestMethod -Uri $url -Method POST -Headers $requestHeader -Body $requestBody

$Header = @{
    Authorization  = "Bearer " + $response.access_token
    'Content-Type' = 'application/json'
}

Invoke-WebRequestInvoke-RestMethod で LINE WORKS API 2.0 を呼び出す際に、-Headers$Header オブジェクトを渡してあげれば、PowerShell から LINE WORKS API 2.0 が利用できます。

これで、PowerShell から LINE WORKS API 2.0 を呼び出す準備ができました。

2022/5/20 追記
powershell-jwt の利用には、PowerShell 6.2 以降が必要です。

5
4
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
5
4