Skip to content
Client Plugin

Ktor 客户端中的认证与授权

所需依赖项: io.ktor:ktor-client-auth

Ktor 提供了 Auth 插件,用于处理客户端应用程序中的认证与授权。典型的用法场景包括用户登录和获取特定资源的访问权限。

在服务器端,Ktor 提供了 Authentication 插件用于处理认证与授权。

支持的认证类型

HTTP 提供了用于 访问控制与认证的通用框架。Ktor 客户端允许你使用以下 HTTP 认证方案:

  • Basic - 使用 Base64 编码来提供用户名和密码。除非与 HTTPS 结合使用,否则通常不推荐。
  • Digest - 一种认证方法,通过对用户名和密码应用散列函数,以加密形式传输用户凭据。
  • Bearer - 一种认证方案,涉及称为持有者令牌的安全令牌。例如,你可以将此方案作为 OAuth 流程的一部分,通过使用 Google、Facebook、Twitter 等外部提供者来授权应用程序用户。

添加依赖项

要启用认证,你需要在构建脚本中包含 ktor-client-auth artifact:

Kotlin
Groovy
XML

你可以从

添加客户端依赖项
了解如何向现有项目添加客户端依赖项。
中了解更多关于 Ktor 客户端所需的 artifact。

安装 Auth

要安装 Auth 插件,请将其传递给 客户端配置块 中的 install 函数:

kotlin
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.auth.*
//...
val client = HttpClient(CIO) {
    install(Auth) {
        // 配置认证
    }
}

现在你可以配置所需的认证提供者。

配置认证

步骤 1:选择认证提供者

要使用特定的认证提供者(BasicDigestBearer),你需要调用 install 代码块内相应的函数。例如,要使用 basic 认证,请调用 basic 函数:

kotlin
install(Auth) {
    basic {
        // 配置 Basic 认证
    }
}

在该代码块内,你可以配置此提供者特有的设置。

步骤 2:(可选)配置域

可选地,你可以使用 realm 属性来配置域:

kotlin
install(Auth) {
    basic {
        realm = "Access to the '/' path"
        // ...
    }
}

你可以创建多个具有不同域的提供者,以访问不同的资源:

kotlin
install(Auth) {
    basic {
        realm = "Access to the '/' path"
        // ...
    }
    basic {
        realm = "Access to the '/admin' path"
        // ...
    }
}

在这种情况下,客户端会根据 WWW-Authenticate 响应标头选择必要的提供者,该标头中包含域信息。

步骤 3:配置提供者

要了解如何配置特定提供者的设置,请参阅相应的专题: