LDAP
Required dependencies: io.ktor:ktor-auth
, io.ktor:ktor-auth-ldap
Code example: auth-ldap
LDAP is a protocol for working with various directory services that can store information about users. Ktor allows you to authenticate LDAP users using the basic, digest, or form-based authentications schemes.
tip
You can get general information about authentication and authorization in Ktor in the Authentication and authorization section.
Add dependencies
To enable LDAP
authentication, you need to include the ktor-auth
and ktor-auth-ldap
artifacts in the build script:
implementation "io.ktor:ktor-auth:$ktor_version"
implementation "io.ktor:ktor-auth-ldap:$ktor_version"
implementation("io.ktor:ktor-auth:$ktor_version")
implementation("io.ktor:ktor-auth-ldap:$ktor_version")
<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-auth</artifactId>
<version>${ktor_version}</version>
</dependency>
<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-auth-ldap</artifactId>
<version>${ktor_version}</version>
</dependency>
Configure LDAP
Step 1: Choose an authentication provider
To authenticate LDAP users, you first need to choose an authentication provider for username and password validation. In Ktor, the basic, digest, or form-based providers can be used for this. For example, to use the basic
authentication provider, call the basic function inside the install
block.
install(Authentication) {
basic {
validate { credentials ->
// Authenticate an LDAP user
}
}
}
The validate function will be used to check user credentials.
Step 2: Authenticate an LDAP user
To authenticate an LDAP user, you need to call the ldapAuthenticate function. This function accepts UserPasswordCredential and validates it against a specified LDAP server.
install(Authentication) {
basic("auth-ldap") {
validate { credentials ->
ldapAuthenticate(credentials, "ldap://0.0.0.0:389", "cn=%s,dc=ktor,dc=io")
}
}
}
The validate
function returns a UserIdPrincipal in a case of successful authentication or null
if authentication fails.
Optionally, you can add additional validation for an authenticated user.
install(Authentication) {
basic("auth-ldap") {
validate { credentials ->
ldapAuthenticate(credentials, "ldap://localhost:389", "cn=%s,dc=ktor,dc=io") {
if (it.name == it.password) {
UserIdPrincipal(it.name)
} else {
null
}
}
}
}
}
Step 3: Define authorization scope
After configuring LDAP, you can define the authorization for the different resources in our application using the authenticate
function. In a case of successful authentication, you can retrieve an authenticated UserIdPrincipal inside a route handler using the call.principal function and get a name of an authenticated user.
routing {
authenticate("auth-ldap") {
get("/") {
call.respondText("Hello, ${call.principal<UserIdPrincipal>()?.name}!")
}
}
}
You can find the complete runnable example here: auth-ldap.
tip
Bear in mind that current LDAP implementation is synchronous.