Search code examples
kotlinktor

Where should I put secrets if I'm using embeddedServer?


I have google oauth credentials, and a google application password to send emails, I wanna know where should I put this information if I'm using embeddedServer

If you are using EngineMain, Ktor docs are clear (use application.conf or application.yaml), but there are no answer for when you are using embeddedServer. I don't wanna put this information in my code.

I tried to create application.conf in the resources folder and then retrieve the data using:

val googleClientId = environment.config.propertyOrNull("ktor.deployment.GOOGLE_CLIENT_ID")?.getString() ?: ""

However, the function always returns null

Anyone knows where to put secrets when you are using embeddedServer?


Solution

  • You can pass your secrets through the environment variables to your application or use an external secrets storage. Storing secrets in a configuration file isn't safe. To use a configuration file with the embeddedServer, pass an environment as the second argument:

    val env = applicationEngineEnvironment {
        connector {
            port = 8080
        }
        config = ApplicationConfig("application.conf")
        module {
            routing {
                get {
                    call.respondText { application.environment.config.propertyOrNull("ktor.deployment.GOOGLE_CLIENT_ID")!!.getString() }
                }
            }
        }
    }
    val server = embeddedServer(Netty, env)
    server.start(wait = true)
    

    Also, you can use a configuration instance not bound to the application:

    val config = ApplicationConfig("application.conf")
    val server = embeddedServer(Netty, port = 8080) {
        routing {
            get {
                call.respondText { config.propertyOrNull("ktor.deployment.GOOGLE_CLIENT_ID")!!.getString() }
            }
        }
    }
    server.start(wait = true)