Authentication

suggest change

Authentication verifies the identity of a client attempting to access restricted resources. In Kotlin backend systems (such as Ktor or Spring Boot), authentication typically involves secure password hashing, token validation (such as Bearer or JWT), Basic HTTP auth, or API key validation.


Secure Password Hashing with BCrypt

Passwords should never be stored in plaintext. Use an adaptive, salted hashing algorithm such as BCrypt or Argon2.

Add the BCrypt library to build.gradle.kts:

dependencies {
    implementation("at.favre.lib:bcrypt:0.10.2")
}

Hashing and Verifying Passwords

import at.favre.lib.crypto.bcrypt.BCrypt

object PasswordHasher {
    // Work factor (cost): 12 iterations (adjust based on hardware performance)
    private const val COST = 12

    fun hashPassword(password: String): String {
        return BCrypt.withDefaults().hashToString(COST, password.toCharArray())
    }

    fun verifyPassword(password: String, bcryptHash: String): Boolean {
        val result = BCrypt.verifyer().verify(password.toCharArray(), bcryptHash.toCharArray())
        return result.verified
    }
}

fun main() {
    val rawPassword = "CorrectHorseBatteryStaple!"
    
    // Hash before saving to database
    val hash = PasswordHasher.hashPassword(rawPassword)
    println("Stored Hash: $hash")

    // Verify during login
    val isValid = PasswordHasher.verifyPassword(rawPassword, hash)
    println("Password valid? $isValid") // true

    val isWrong = PasswordHasher.verifyPassword("WrongPassword", hash)
    println("Wrong password valid? $isWrong") // false
}

Authentication in Ktor

Ktor provides a first-class Authentication plugin supporting multiple concurrent authentication mechanisms.

Add Ktor authentication plugins:

dependencies {
    implementation("io.ktor:ktor-server-auth:3.6.0")
    implementation("io.ktor:ktor-server-auth-jwt:3.6.0")
}

Basic Authentication

Basic Authentication validates credentials sent in the Authorization: Basic <base64> header:

import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.response.*
import io.ktor.server.routing.*

fun Application.configureBasicAuth() {
    install(Authentication) {
        basic(name = "auth-basic") {
            realm = "Access to protected admin area"
            validate { credentials ->
                if (credentials.name == "admin" && credentials.password == "supersecret") {
                    UserIdPrincipal(credentials.name)
                } else {
                    null
                }
            }
        }
    }

    routing {
        // Public route
        get("/") {
            call.respondText("Public endpoint")
        }

        // Protected route
        authenticate("auth-basic") {
            get("/admin") {
                val principal = call.principal<UserIdPrincipal>()!!
                call.respondText("Welcome to Admin, ${principal.name}!")
            }
        }
    }
}

JWT / Bearer Token Authentication

Bearer token authentication allows stateless verification of incoming JSON Web Tokens:

import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.response.*
import io.ktor.server.routing.*

fun Application.configureJwtAuth() {
    val jwtSecret = "your-256-bit-secret"
    val jwtIssuer = "https://auth.example.com"
    val jwtAudience = "https://api.example.com"

    install(Authentication) {
        jwt("auth-jwt") {
            realm = "Access to protected API"
            verifier(
                JWT.require(Algorithm.HMAC256(jwtSecret))
                    .withAudience(jwtAudience)
                    .withIssuer(jwtIssuer)
                    .build()
            )
            validate { credential ->
                if (!credential.payload.getClaim("username").asString().isNullOrEmpty()) {
                    JWTPrincipal(credential.payload)
                } else {
                    null
                }
            }
        }
    }

    routing {
        authenticate("auth-jwt") {
            get("/api/profile") {
                val principal = call.principal<JWTPrincipal>()!!
                val username = principal.payload.getClaim("username").asString()
                val role = principal.payload.getClaim("role").asString() ?: "user"

                call.respondText("User: $username, Role: $role")
            }
        }
    }
}

API Key Header Authentication with Constant-Time Comparison

When building internal APIs or webhook endpoints, clients often authenticate via an X-API-Key header. When comparing keys, use constant-time byte comparisons to prevent timing side-channel attacks:

import java.security.MessageDigest

class ApiKeyValidator(private val expectedApiKey: String) {

    fun isValid(providedKey: String?): Boolean {
        if (providedKey == null) return false

        val expectedBytes = expectedApiKey.toByteArray(Charsets.UTF_8)
        val providedBytes = providedKey.toByteArray(Charsets.UTF_8)

        // Constant-time comparison prevents timing attacks
        return MessageDigest.isEqual(expectedBytes, providedBytes)
    }
}

Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents