概要
(日記)Google Driveアプリのデータを参照したいと思ったので、Google OAuth2で認証しアクセストークン取得まで
環境
- Google Cloud のプロジェクト
- Windwos 11
- Java 21 (for gradlew)
//# SpreadsheetのクラウドAPIを有効にする
//Google Cloudのメニューから[APIとサービス]
//➔ [APIとサービスを有効にする] ➜ [Google Sheets API]を選択 ➜ [有効にする]
Google CloudでOAuthを設定
Google Cloudのメニューから[APIとサービス]➜[OAuth同意画面]
デベロッパーの連絡先情報以外はデフォルト値のまま[保存して次へ]
ここでは刷新されたUIを使ってみます[新しいページに移動]
[スコープを追加または削除]➜フィルタでGoogle Sheets APIを入力、今回は readonlyを指定。➔[SAVE]
クライアント登録
Google Cloudのメニューから[APIとサービス]➜[認証情報]➜[認証情報を作成]➜[OAuthクライアントID]➜デスクトップ クライアントを作成
GOOGLE_CLIENT_IDとGOOGLE_CLIENT_SECRETを入手
コード
build.gradle.kts
plugins {
kotlin("jvm") version "2.1.0"
application
}
repositories { mavenCentral() }
application { mainClass = "MainKt" }
dependencies {
implementation("io.ktor:ktor-client-cio:3.0.3")
implementation("io.ktor:ktor-server-cio:3.0.3")
}
src/main/kotiln/Main.kt ※一部略
suspend fun main() {
val client = HttpClient(CIO)
val redirectUri = "http://127.0.0.1:28080"
val authorizationUrl = URLBuilder("https://accounts.google.com/o/oauth2/auth").apply {
parameters.append("client_id", System.getenv("GOOGLE_CLIENT_ID")!!)
parameters.append("redirect_uri", redirectUri)
parameters.append("response_type", "code")
parameters.append("scope", "https://www.googleapis.com/auth/userinfo.profile")
}.buildString()
println("ブラウザで以下のURLを開いて認証してください:\n$authorizationUrl")
// 上で表示されるURLを利用者が開いたブラウザに入力し認証操作を続ける
val authorizationCode = redirectReceiverServer()!! // ここで認証(リダイレクト)を待っている
println("authorizationCode=$authorizationCode")
val tokenResponse = client.submitForm(
url = "https://accounts.google.com/o/oauth2/token",
formParameters = Parameters.build {
append("grant_type", "authorization_code")
append("code", authorizationCode)
append("redirect_uri", redirectUri)
append("client_id", System.getenv("GOOGLE_CLIENT_ID")!!)
append("client_secret", System.getenv("GOOGLE_CLIENT_SECRET")!!)
}
).bodyAsText()
println("accessToken:\n$tokenResponse")
client.close()
}
テスト実行
export GOOGLE_CLIENT_ID='xxxxx......com'
export GOOGLE_CLIENT_SECRET='GO.....RH-2'
sh gradlew shadowJar
java -jar build/libs/Step1-1.0-SNAPSHOT-all.jar
# ターミナルに表示されるURLをブラウザで開きGoogleで認証
accessTokenが表示されればOK.
参照