0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Ktor/OAuth2 でGoogle認証[1]

Last updated at Posted at 2024-12-31

概要

(日記)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.

参照

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?