OAuth 客户端 for Kotlin:用于 API 身份验证的 Ktor OAuth 库

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

OAuth 客户端 for Kotlin:Ktor OAuth 库



Ktor OAuth 库是 Ktor HTTP 客户端的官方扩展,旨在 Kotlin 应用程序中实现 OAuth 2.0 协议。它提供了一种灵活且类型安全的方式,用于集成流行的 OAuth 提供商(Google、GitHub、Facebook、VK 等),并支持自定义端点。该库是 Ktor 生态系统的一部分,可用于服务器端和客户端 Kotlin 应用程序。



主要使用场景是获取访问令牌以使用受保护的 REST API。该库自动化了将授权码交换为令牌、更新令牌(刷新令牌)以及管理会话状态的过程。



主要功能



  • 支持 OAuth 2.0 流程:授权码授权、隐式授权、客户端凭证、资源所有者密码凭证。
  • 内置对流行提供商的支持:Google、GitHub、Facebook、Twitter、VK、Yandex、Microsoft 等。
  • 自定义提供商:能够手动设置授权、令牌和重定向端点。
  • 自动令牌刷新:支持刷新令牌,在访问令牌过期时自动调用。
  • 会话管理:将令牌存储在内存、文件、数据库或自定义存储中。
  • 与 Ktor 客户端集成:通过插件进行统一配置,支持所有传输方式(CIO、Apache、OkHttp)。
  • 安全性:支持 PKCE(Proof Key for Code Exchange)以防止 CSRF 攻击。


安装



要引入该库,请在 build.gradle.kts 中添加依赖项:



dependencies {    // 主要的 Ktor 客户端    implementation("io.ktor:ktor-client-core:2.3.7")    // OAuth 插件    implementation("io.ktor:ktor-client-auth:2.3.7")    // 特定引擎(例如 CIO)    implementation("io.ktor:ktor-client-cio:2.3.7")}


对于 Maven:



<dependency>    <groupId>io.ktor</groupId>    <artifactId>ktor-client-auth</artifactId>    <version>2.3.7</version></dependency>


示例:通过 Google OAuth 进行授权



创建一个配置了 Google OAuth 插件的 HTTP 客户端:



import io.ktor.client.*import io.ktor.client.plugins.auth.*import io.ktor.client.plugins.auth.providers.*import io.ktor.client.request.*import io.ktor.client.statement.*

suspend fun main() { val client = HttpClient { install(Auth) { oauth { clientId = System.getenv("GOOGLE_CLIENT_ID") clientSecret = System.getenv("GOOGLE_CLIENT_SECRET") providerLookup = { OAuthServerSettings.OAuthAuthorizationCodeServerSettings( authorizeUrl = "https://accounts.google.com/o/oauth2/auth", tokenUrl = "https://oauth2.googleapis.com/token", clientId = clientId, clientSecret = clientSecret, redirectUrl = "http://localhost:8080/callback" ) } urlProvider = { request -> // 生成用于重定向用户的 URL "http://localhost:8080/login" } } } }

// 向 Google Sheets API 发送请求的示例 val response: HttpResponse = client.get("https://sheets.googleapis.com/v4/spreadsheets/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgVE2upms/values/Sheet1!A1:D5") println(response.bodyAsText())}


示例:带有 PKCE 的自定义提供商



为了提高安全性,请使用 PKCE(P

推荐