Auth

预计阅读时间: 2 分钟

Ktor client supports authentication out of the box as a standard pluggable feature:

本特性在构件 io.ktor:ktor-client-auth:$ktor_version 中的 io.ktor.client.features.auth.Auth 类中定义
dependencies { implementation "io.ktor:ktor-client-auth:$ktor_version" }
dependencies { implementation("io.ktor:ktor-client-auth:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-auth</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies> </project>
dependencies { implementation "io.ktor:ktor-client-auth-jvm:$ktor_version" }
dependencies { implementation("io.ktor:ktor-client-auth-jvm:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-auth-jvm</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies> </project>
dependencies { implementation "io.ktor:ktor-client-auth-native:$ktor_version" }
dependencies { implementation("io.ktor:ktor-client-auth-native:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-auth-native</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies> </project>
dependencies { implementation "io.ktor:ktor-client-auth-js:$ktor_version" }
dependencies { implementation("io.ktor:ktor-client-auth-js:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-auth-js</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies> </project>

Installation

val client = HttpClient() {
    install(Auth) {
        // providers config
        ...
    }
}

Providers

Basic

This provider sends an Authorization: Basic with the specified credentials:

val client = HttpClient() {
    install(Auth) {
        basic {
            username = "username"
            password = "password"
        }
    }
}

This feature implements the IETF’s RFC 7617.

Digest

This provider sends an Authorization: Digest with the specified credentials:

val client = HttpClient() {
    install(Auth) {
        digest {
            username = "username"
            password = "password"
            realm = "custom"
        }
    }
}

This feature implements the IETF’s RFC 2617.