LINE WORKS API トークンを取得する方法
この記事では、LINE WORKS API を実行するためのアクセストークン取得手順を解説します。LINE WORKS API の利用にはアクセストークンが必要ですが、JWT 認証を使った少し特別な方法が必要です。このサンプルでは、API リファレンスを基に、アクセストークンを取得するスクリプトを作成し Google Colab で試してみます。
必要な準備
まず、LINE WORKS Developer Console のアプリで以下の情報を取得してください:
- CLIENT_ID:API クライアント ID
- CLIENT_SECRET:API クライアントシークレット
- SERVICE_ACCOUNT:サービスアカウントのメールアドレス
- DOMAIN_ID:ドメイン ID
- SCOPE:スコープ(API の種類に応じて "bot" などを指定)
また、JWT 認証のための秘密鍵ファイル(*.key
ファイルなど)も必要です。
スクリプト
アクセストークンを取得するためのサンプルスクリプトを以下に示します。
以下の URL で Google Colab で試せます。
https://colab.research.google.com/drive/1oTEJoAG7l9lE0CU48lM0lsZ4XRXRsUHi?usp=sharing
# 必要な情報の設定
CLIENT_ID = "あなたのCLIENT_ID" # @param {type:"string"}
CLIENT_SECRET = "あなたのCLIENT_SECRET" # @param {type:"string"}
SERVICE_ACCOUNT = "あなたのSERVICE_ACCOUNT" # @param {type:"string"}
DOMAIN_ID = "あなたのDOMAIN_ID" # @param {type:"string"}
SCOPE = "bot" # @param {type:"string"}
# Google Colab 上で秘密鍵ファイルをアップロード
from google.colab import files
uploaded = files.upload()
PRIVATE_KEY_PATH = list(uploaded.keys())[0]
with open(PRIVATE_KEY_PATH, 'r') as file:
PRIVATE_KEY = file.read()
# 必要なライブラリのインポート
import jwt
import time
import json
import requests
from datetime import datetime, timedelta
# JWTのHeaderとPayloadを設定
header = {
"alg": "RS256",
"typ": "JWT"
}
# 現在のUTC時刻を取得して、iatとexpを設定
current_time = datetime.utcnow()
iat = int(time.mktime(current_time.timetuple()))
exp = int(time.mktime((current_time + timedelta(hours=1)).timetuple()))
payload = {
"iss": CLIENT_ID,
"sub": SERVICE_ACCOUNT,
"iat": iat,
"exp": exp
}
# JWTの生成
assertion = jwt.encode(payload, PRIVATE_KEY, algorithm="RS256", headers=header)
# POSTリクエストのためのデータを準備
data = {
'assertion': assertion,
'grant_type': "urn:ietf:params:oauth:grant-type:jwt-bearer",
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'scope': SCOPE
}
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
# API エンドポイントに POST リクエストを送信してトークンを取得
response = requests.post('https://auth.worksmobile.com/oauth2/v2.0/token', data=data, headers=headers)
# 応答の確認
if response.status_code == 200:
token_info = response.json()
access_token = token_info.get('access_token')
print(f"アクセストークン: {access_token}")
else:
print(f"Failed to retrieve token. Status code: {response.status_code}, Response: {response.text}")