iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🧪

How to Use the OAuth Plugin in Ktor

に公開
2024/09/17
3件

Since Ktor v2.0.0 was about to be officially released, I decided to dive into it properly and have been researching Ktor Server lately. (In fact, it was released on April 11th 🎉)

https://zenn.dev/yamachoo/scraps/4a1f8177812968

https://blog.jetbrains.com/ktor/2022/04/11/ktor-2-0-released/

At that time, I couldn't quite grasp the image of Ktor's OAuth functionality just by looking it up, so I tried implementing it myself.
When I did, I ran into some unexpected hurdles, so I've written this article as a memo for myself.

Prerequisites

The development environment not mentioned in the article is as follows:

Gradle: 7.1.1
Kotlin: 1.6.20
JVM: 17.0.1 (Amazon.com Inc. 17.0.1+12-LTS)
Ktor: 2.0.0

By the way, this assumes that the Ktor project was created using the Ktor Project Generator without adding any additional plugins.

OAuth Preparation

Since we will use Google OAuth for this implementation, set up the "OAuth consent screen" and "Credentials" on Google Cloud Platform beforehand to obtain a Client ID and Client Secret.

In my case, I created a .env file, set the Client ID and Client Secret as environment variables, and load them using direnv.

.env
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=

Installing necessary Ktor plugins

First, add the necessary Ktor plugins to build.gradle.kts.

build.gradle.kts
dependencies {
    implementation("io.ktor:ktor-server-auth:$ktor_version")
    implementation("io.ktor:ktor-server-sessions:$ktor_version")
    implementation("io.ktor:ktor-client-core:$ktor_version")
    implementation("io.ktor:ktor-client-apache:$ktor_version")
}

Using Google OAuth 2.0

First, create an additional file Security.kt under the plugins directory. By writing the code as follows, we use Google OAuth 2.0.

plugins/Security.kt
fun Application.configureSecurity() {
    install(Sessions) {
        cookie<UserSession>("user_session")
    }

    install(Authentication) {
        oauth("auth-oauth-google") {
            urlProvider = { "http://localhost:8080/callback" }
            providerLookup = {
                OAuthServerSettings.OAuth2ServerSettings(
                    name = "google",
                    authorizeUrl = "https://accounts.google.com/o/oauth2/auth",
                    accessTokenUrl = "https://accounts.google.com/o/oauth2/token",
                    requestMethod = HttpMethod.Post,
                    clientId = System.getenv("GOOGLE_CLIENT_ID"),
                    clientSecret = System.getenv("GOOGLE_CLIENT_SECRET"),
                    defaultScopes = listOf("https://www.googleapis.com/auth/userinfo.profile")
                )
            }
            client = HttpClient(Apache)
        }
    }

    routing {
        authenticate("auth-oauth-google") {
            get("/login") {}

            get("/callback") {
                val principal: OAuthAccessTokenResponse.OAuth2? = call.authentication.principal()
                call.sessions.set(UserSession(principal?.accessToken.toString()))
                call.respondRedirect("/hello")
            }
        }
    }
}

data class UserSession(val accessToken: String)

However, because it's hard to understand just by looking at the code as a whole, I'll break it down into three important sections for explanation.

Implementing OAuth

First, this is the part where OAuth is implemented using the plugin.

install(Authentication) loads the Authentication plugin, and oauth("auth-oauth-google") creates an OAuth provider named auth-oauth-google.

In the oauth block, the urlProvider property specifies the URL to redirect to after authorization is complete, and the providerLookup property specifies the OAuth settings for the required provider. Finally, the client property specifies the HttpClient used to send requests to the OAuth server.

install(Authentication) {
    oauth("auth-oauth-google") {
        urlProvider = { "http://localhost:8080/callback" }
        providerLookup = {
            OAuthServerSettings.OAuth2ServerSettings(
                name = "google",
                authorizeUrl = "https://accounts.google.com/o/oauth2/auth",
                accessTokenUrl = "https://accounts.google.com/o/oauth2/token",
                requestMethod = HttpMethod.Post,
                clientId = System.getenv("GOOGLE_CLIENT_ID"),
                clientSecret = System.getenv("GOOGLE_CLIENT_SECRET"),
                defaultScopes = listOf("https://www.googleapis.com/auth/userinfo.profile")
            )
        }
        client = HttpClient(Apache)
    }
}

Implementing Sessions

Next, I will explain the part where sessions are configured.

In this section, a session called UserSession is defined using a data class, and the session is stored in a cookie named user_session.
This allows you to use call.sessions.set() and call.sessions.get<UserSession>().

fun Application.configureSecurity() {
    install(Sessions) {
        cookie<UserSession>("user_session")
    }

    ... // omitted
}

data class UserSession(val accessToken: String)

Implementing Routing

Finally, there is the routing section, where the actual routing takes place.

Accessing /login triggers the OAuth process, and upon successful authentication, you are redirected to /callback where the subsequent processing occurs.
In this case, we extract the authentication information at /callback, save the accessToken in the session, and then redirect to /hello.
(*Note: This implementation is a temporary setup for verification; please do not save the accessToken directly in the session in a production environment.)

Also, get("/login") {} might look a bit strange, but it works even if it's empty because authenticate("auth-oauth-google") automatically redirects to the urlProvider.

routing {
    authenticate("auth-oauth-google") {
        get("/login") {}

        get("/callback") {
            val principal: OAuthAccessTokenResponse.OAuth2? = call.authentication.principal()
            call.sessions.set(UserSession(principal?.accessToken.toString()))
            call.respondRedirect("/hello")
        }
    }
}

Other Implementations and Startup

In Routing.kt, the redirect destination implemented in Security.kt is newly added.

plugins/Routing.kt
fun Application.configureRouting() {
    routing {
        get("/") {
            call.respondText("Hello World!")
        }
+
+       get("/hello") {
+           call.respondText("Hello World!\n${call.sessions.get<UserSession>()?.accessToken}")
+       }
    }
}

Also, in Application.kt, the configureSecurity created in Security.kt is newly loaded.

Application.kt
fun main(args: Array<String>): Unit =
    io.ktor.server.netty.EngineMain.main(args)

@Suppress("unused") // application.conf references the main function. This annotation prevents the IDE from marking it as unused.
fun Application.module() {
    configureRouting()
+   configureSecurity()
}

Finally, start the application with ./gradlew run and access http://localhost:8080/login to confirm that OAuth is working. If authentication is successful, you will be redirected to http://localhost:8080/hello, and you should be able to see "Hello World!" and your accessToken.

Conclusion

This concludes the basic verification of using Google OAuth 2.0.
However, in a real-world scenario, you would also need to implement user registration and design routing for multiple OAuth providers.

Also, as pointed out by ritou, it is better to use the OpenID Connect mechanism when implementing login authentication via OAuth, so I'm adding that note here.

https://developers.google.com/identity/protocols/oauth2/openid-connect

Therefore, in the future, I'd like to further refine the implementation around login by building a more practical application.

References

https://ktor.io/docs/oauth.html

https://github.com/ktorio/ktor-documentation/tree/main/codeSnippets/snippets/auth-oauth-google

By the way, I've also included an implementation sample I created for your reference.

https://github.com/yamachoo/ktor-oauth-sample

Discussion

ritouritou

こちらの目的であれば、GoogleはOAuth 2.0にユーザー情報などを受け渡しする仕組みを追加したOpenID Connect(≠OAuth認証)という仕様に沿った仕組みが提供されていますのでそれを利用すべきです。

参考URL : https://developers.google.com/identity/protocols/oauth2/openid-connect

今回の記事の内容では

  • セッションにアクセストークンを保存
  • 今後はそのセッションに含まれたアクセストークンから対象ユーザーを把握できる

と言う意味合いになっているかと思いますが、ID連携のベストプラクティスとしては

  • callback時にGoogleからユーザー情報を取得する
  • そのユーザー情報のユーザー識別子を用いてアプリケーション内部のユーザーDBなどを参照し、紐付けがあるユーザーのログインセッションを発行する。場合によってはアクセストークンを内部のユーザーIDと紐付けて保存しておく
  • その後はアプリケーション内のセッション機構を利用する

と言うものです。
上記Googleのドキュメントにもこの辺りの流れが記載されていると思いますので、ぜひお時間のあるときにご覧いただいて今後の参考にしていただければと思います。

1
YamarYamar

ご指摘ありがとうございます!

一応、今回の記事の内容としては

  • セッションにアクセストークンを保存
  • 今後はそのセッションに含まれたアクセストークンから対象ユーザーを把握できる

というよりはKtorのOAuthプラグインの使い方を解説し、セッションに保存したアクセストークンはデータが取れていることの確認とその後の表示の確認くらいの認識の実装で済ましてしまっていたので、「OAuth認証」というタイトルをつけてしまったことなども良くなかったかもです💦
(「KtorでOAuthプラグインを利用する方法」が正しいかもしれないと考え中です)

そのため、今後、記事を読まれる方が誤解しないようタイトルや記述の一部を修正しようと思います。
また差し支えなければ、ritou様のお名前とOpenID Connectについてのご指摘を「さいごに」に付け加えさせていただきたいと思っています。

また教えていただいたOpenID Connectの実装は、今後のログインの実装の際に参考にさせていただきます!

自分としても間違った情報を拡散してしまうことは本意ではないので、今後とも間違いなどありましたら、ご指摘いただけるとありがたいです!

YamarYamar

修正をさせていただきました。
もし気になる箇所がありましたら、ご指摘いただけると幸いです。