3

I've been banging my head against the wall trying to figure out what's going wrong here for a while. I created a simple Ktor server that allows you to create a user, which should return a token to the user and store the session. Then I want an authenticated endpoint to allow the user to be deleted. However, the authenticated call loads an empty session, and can't find the user, so the user can't be deleted. Any help would be appreciated! Code here:

Application.kt

...
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)

@Suppress("unused") 
@kotlin.jvm.JvmOverloads
fun Application.module(testing: Boolean = false) {
    install(Locations) {
    }

    install(Sessions) {
        cookie<MySession>("MY_SESSION") {
            cookie.extensions["SameSite"] = "lax"
        }
    }

    DatabaseFactory.init()
    val db = MyRepository()
    val jwtService = JwtService()
    val hashFunction = { s: String -> hash(s) }

    install(Authentication) {
        jwt("jwt") { //1
            verifier(jwtService.verifier) // 2
            realm = "My Server"
            validate { // 3
                val payload = it.payload
                val claim = payload.getClaim("id")
                val claimString = claim.asInt()
                val user = db.findUser(claimString) // 4
                user
            }
        }
    }

    install(ContentNegotiation) {
        gson {
        }
    }

    routing {
        users(db, jwtService, hashFunction)
    }
}

UserRoute.kt

...
const val USERS = "$API_VERSION/users"
const val USER_CREATE = "$USERS/create"
const val USER_DELETE = "$USERS/delete"

@KtorExperimentalLocationsAPI
@Location(USER_CREATE)
class UserCreateRoute

@KtorExperimentalLocationsAPI
@Location(USER_DELETE)
class UserDeleteRoute

@KtorExperimentalLocationsAPI
fun Route.users(
    db: Repository,
    jwtService: JwtService,
    hashFunction: (String) -> String
) {
    post<UserCreateRoute> {
        val request = call.receive<CreateUserRequest>()
        val password = request.password
            ?: return@post call.respond(
                HttpStatusCode.Unauthorized, "Missing Fields")
        val email = request.email
            ?: return@post call.respond(
                HttpStatusCode.Unauthorized, "Missing Fields")
        val hash = hashFunction(password)
        try {
            val newUser = db.addUser(email, hash)
            newUser?.userId?.let {
                call.sessions.set(MySession(it))
                call.respondText(
                    jwtService.generateToken(newUser),
                    status = HttpStatusCode.Created
                )
            }
        } catch (e: Throwable) {
            call.respond(HttpStatusCode.BadRequest, "Problems creating User")
        }
    }
   
    authenticate("jwt") {
        delete<UserDeleteRoute> {
            try {
                val userId = call.sessions.get<MySession>()?.userId

                if (userId == null) {
                    call.respond(
                        HttpStatusCode.BadRequest, "Problem retrieving User")
                    return@delete
                }

                if (db.deleteUser(userId)) {
                    call.respond(HttpStatusCode.NoContent, "User deleted")
                } else {
                    call.respond(HttpStatusCode.BadRequest, "Failed to delete user")
                }
            } catch (e: Exception) {
                application.log.error("Failed to delete user")
                call.respond(HttpStatusCode.BadRequest, "Failed to delete user")
            }
        }
    }
}

Is there something I'm missing? The token is returned successfully, and then my delete request is routed to the right place, but the line val userId = call.sessions.get<MySession>()?.userId returns null every time.

1
  • Do you have a sample project to try and reproduce this? Jun 30, 2020 at 8:13

1 Answer 1

0

You don't show the client code but it is just as important. Likely the problem is on the client not on server. When the clients does the delete does it send the token?

jwt would be more complicated for for basic auth after you get a session each request must include the session header:

curl  -H "MY_SESSION: f152dad6e955ba53" -D - localhost:8080/api/admin/principle

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.