googleapisの認証情報を作る
アプリにGoogleDriveのクレデンシャルを渡したいが、これどうやれば良いんだっけって毎回なるのでいい加減書き残します code:bash
pip3 install -U oauth2client
Pythonで以下のコードを動かします
code:py
import oauth2client.client
import oauth2client.tools
import oauth2client.file
clientid_path = "ダウンロードしたJSON"
credential_path = "アクセストークンファイル作成先のパス"
def main():
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = oauth2client.client.flow_from_clientsecrets(clientid_path, scope)
credentials = oauth2client.tools.run_flow(flow, store)
print("done")
main()
実行するとブラウザが開く
oauth2clientはディスコンっぽく、Google OAuthでoobが廃止されても対応がなされていないので、--no_local_webserverは使えません 「ダウンロードしたJSON」「アクセストークンファイル作成先のパス」を1行にする
jqが必要です 入ってなかったら入れてください
code:bash
cat ダウンロードしたJSON | jq .installed -c
cat アクセストークンファイル作成先のパス | jq -c
それぞれ環境変数にする
code:env
export GOOGLEAPIS_CLIENT_ID='ダウンロードしたJSONをjqしたやつ'
export GOOGLEAPIS_CREDENTIAL='アクセストークンファイル作成先のパスをjqしたやつ'
読む
code:ts
import { google } from "googleapis"
import * as $ from "zod"
// 必須ではない
export const googleapisClientIdValidator = $.object({
project_id: $.string(),
client_id: $.string(),
auth_uri: $.string(),
token_uri: $.string(),
auth_provider_x509_cert_url: $.string(),
client_secret: $.string(),
redirect_uris: $.array($.string()),
})
export const googleapisCredentialValidator = $.object({
access_token: $.string(),
refresh_token: $.string(),
scopes: $.array($.string()),
token_response: $.object({
token_type: $.string(),
scope: $.string(),
}),
})
const main = async() => {
const clientId = googleapisClientIdValidator.parse(
JSON.parse(googleapisClientId)
)
const credential = googleapisCredentialValidator.parse(
JSON.parse(googleapisCredential)
)
const auth = new google.auth.OAuth2(
clientId.client_id,
clientId.client_secret,
)
auth.setCredentials({
refresh_token: credential.refresh_token,
access_token: credential.access_token,
token_type: credential.token_response.token_type,
scope: credential.scopes0, })
const client = google.drive({ version: "v3", auth })
}
前はsetCredentialsにガッチリハマるのが吐き出されてたんですが、今日やってみたらちょっと構造をいじる必要があるようになっていた
oauth2client使ってるのが悪かったりして