GuardAPI Logo
GuardAPI

Fix BOLA (Broken Object Level Authorization) in Ktor

BOLA (Broken Object Level Authorization), formerly known as IDOR, remains the most critical vulnerability in modern API architectures. In Ktor, this occurs when a route handler processes an object identifier from the request path or body without verifying that the authenticated principal has the requisite permissions to access that specific resource. Attackers exploit this by iterating IDs to scrape data or manipulate records belonging to other users.

The Vulnerable Pattern

get("/api/invoices/{id}") {
    val id = call.parameters["id"]?.toInt() ?: return@get call.respond(HttpStatusCode.BadRequest)
    // VULNERABLE: Only checks if the object exists, not who owns it
    val invoice = db.findInvoiceById(id) 
    if (invoice == null) {
        call.respond(HttpStatusCode.NotFound)
    } else {
        call.respond(invoice)
    }
}

The Secure Implementation

The fix shifts authorization logic from 'Does this object exist?' to 'Does this object belong to the requester?'. By extracting the 'user_id' directly from the cryptographically signed JWTPrincipal, we establish a trusted identity. The database layer is then modified to include this 'userId' in the 'WHERE' clause of the query. This ensures that even if an attacker guesses a valid 'invoiceId', the application layer will fail to retrieve the record because the ownership check fails at the data access level.

authenticate("auth-jwt") {
    get("/api/invoices/{id}") {
        val principal = call.principal()
        val userId = principal?.payload?.getClaim("user_id")?.asInt() 
            ?: return@get call.respond(HttpStatusCode.Unauthorized)
    val invoiceId = call.parameters["id"]?.toInt() ?: return@get call.respond(HttpStatusCode.BadRequest)

    // SECURE: Query explicitly filters by the authenticated user's ID
    val invoice = db.findInvoiceForUser(invoiceId, userId)
    
    if (invoice == null) {
        // Use 404 to avoid leaking resource existence to unauthorized parties
        call.respond(HttpStatusCode.NotFound)
    } else {
        call.respond(invoice)
    }
}

}

System Alert • ID: 7804
Target: Ktor API
Potential Vulnerability

Your Ktor API might be exposed to BOLA (Broken Object Level Authorization)

74% of Ktor apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.