Search code examples
kotlinktor

Sharing data between plugins in Ktor


I created a plugin that takes settings from application.conf file

fun Application.getEnvironment() {
    val secret = environment.config.property("jwt.secret").getString()
    val issuer = environment.config.property("jwt.issuer").getString()
    val audience = environment.config.property("jwt.audience").getString()
    val realm = environment.config.property("jwt.realm").getString()
}

Now I would like to use these environment properties in different plugin like the following:

fun Application.configureJWTAuth() {
    val (secret, issuer, audience, realm) = getEnvironment()

   // configuring jwt with properties taken from `getEnvironment()`
}

However I have no idea how to solve the problem. I know I can create a global object and assign properties to this global object in getEnvironment() plugin but I do not think it is the best solution.


Solution

  • You can use Attributes of the server application instance to store and access global data. Here is an example:

    val jwtSecretKey = io.ktor.util.AttributeKey<String>("jwtSecret")
    val plugin1 = createApplicationPlugin("plugin1") {
        application.attributes.put(jwtSecretKey, "jwt secret value")
    }
    
    val plugin2 = createApplicationPlugin("plugin2") {
        val jwtSecret = application.attributes.getOrNull(jwtSecretKey)
        println(jwtSecret)
    }
    
    suspend fun main() {
        embeddedServer(Netty, host = "localhost", port = 9090) {
           install(plugin1) // the order of plugins matters
           install(plugin2)
        }.start(wait = true)
    }