Skip to content

Ktor Client 中的 Digest 驗證 ​

必要相依性:io.ktor:ktor-client-auth

程式碼範例: client-auth-digest

在 Digest 驗證機制中,使用者名稱和密碼在透過網路傳送之前,會先經過雜湊函式處理。

在伺服器端,Ktor 提供了 Authentication 外掛程式來處理 Digest 驗證。

新增相依性 ​

若要啟用驗證,請在建置指令碼中包含 ktor-client-auth 產物:

kotlin
implementation(ktorLibs.client.auth)
上述程式碼片段使用 Ktor 版本目錄 (version catalog) 來指定 Ktor 相依性。
groovy
implementation ktorLibs.client.auth
上述程式碼片段使用 Ktor 版本目錄 (version catalog) 來指定 Ktor 相依性。
xml
<dependency>
    <groupId>io.ktor</groupId>
    <artifactId>ktor-client-auth-jvm</artifactId>
    <version>${ktor_version}</version>
</dependency>
若要進一步了解 Ktor 用戶端所需的構件,請參閱 新增用戶端相依性了解如何將用戶端相依性新增至現有專案中。。

Digest 驗證流程 ​

Digest 驗證流程如下:

  1. 用戶端向伺服器應用程式中的特定資源發送未包含 Authorization 標頭的請求。

  2. 伺服器回應用戶端 401 (Unauthorized) 回應狀態,並使用 WWW-Authenticate 回應標頭告知該路由使用 Digest 驗證機制進行保護。典型的 WWW-Authenticate 標頭如下所示:

    WWW-Authenticate: Digest
            realm="Access to the '/' path",
            nonce="e4549c0548886bc2",
            algorithm="MD5"
  3. 通常,用戶端會顯示登入對話方塊供使用者輸入憑據。接著,用戶端會發送帶有下列 Authorization 標頭的請求:

    Authorization: Digest username="jetbrains",
            realm="Access to the '/' path",
            nonce="e4549c0548886bc2",
            uri="/",
            algorithm=MD5,
            response="6299988bb4f05c0d8ad44295873858cf"

    response 的值是以如下方式產生:

    a. HA1 = MD5(username:realm:password)

    b. HA2 = MD5(method:digestURI)

    c. response = MD5(HA1:nonce:HA2)

  4. 伺服器驗證用戶端傳送的憑據,並回應所請求的內容。

配置 Digest 驗證 ​

若要使用 Digest 機制在 Authorization 標頭中傳送使用者憑據,您需要依照以下方式配置 digest 驗證提供者:

  1. 在 install 區塊內呼叫 digest 函式。
  2. 使用 DigestAuthCredentials 提供所需的憑據,並將此物件傳遞給 credentials 函式。
  3. (選用)使用 realm 屬性配置領域 (realm)。
kotlin
val client = HttpClient(CIO) {
    install(Auth) {
        digest {
            credentials {
                DigestAuthCredentials(username = "jetbrains", password = "foobar")
            }
            realm = "Access to the '/' path"
        }
    }
}

您可以在此處找到完整的範例:client-auth-digest。