move secrete into config file

This commit is contained in:
2025-03-16 03:40:39 +01:00
parent 4adfc6467c
commit 3434d43fc2
3 changed files with 13 additions and 10 deletions

View File

@@ -15,19 +15,18 @@ import io.ktor.server.routing.routing
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
import java.util.Date import java.util.Date
// TODO: read the jwt property from the config file private const val JWT_ISSUER = "PlayCardGame"
private val jwtRealm = "Play card game"
private val jwtIssuer = "PlayCardGame"
private val jwtSecret = "secret"
fun Application.configureSecurity() { fun Application.configureSecurity() {
val jwtSecret = environment.config.propertyOrNull("jwt.secret")?.getString() ?: error("You must set a jwt secret")
authentication { authentication {
jwt { jwt {
realm = jwtRealm realm = "Play card game"
verifier( verifier(
JWT JWT
.require(Algorithm.HMAC256(jwtSecret)) .require(Algorithm.HMAC256(jwtSecret))
.withIssuer(jwtIssuer) .withIssuer(JWT_ISSUER)
.build(), .build(),
) )
validate { credential -> validate { credential ->
@@ -48,15 +47,15 @@ fun Application.configureSecurity() {
val username = call.parameters["username"]!! val username = call.parameters["username"]!!
val player = Player(name = username) val player = Player(name = username)
call.respond(hashMapOf("token" to player.makeJwt())) call.respond(hashMapOf("token" to player.makeJwt(jwtSecret)))
} }
} }
} }
fun Player.makeJwt(): String = fun Player.makeJwt(jwtSecret: String): String =
JWT JWT
.create() .create()
.withIssuer(jwtIssuer) .withIssuer(JWT_ISSUER)
.withClaim("username", name) .withClaim("username", name)
.withPayload(Json.encodeToString(this)) .withPayload(Json.encodeToString(this))
.withExpiresAt(Date(System.currentTimeMillis() + 60000)) .withExpiresAt(Date(System.currentTimeMillis() + 60000))

View File

@@ -0,0 +1,4 @@
jwt {
secret = "secret"
secret = ${?JWT_SECRET}
}

View File

@@ -117,5 +117,5 @@ class GameStateRouteTest :
}) })
private fun HttpRequestBuilder.withAuth(player: Player) { private fun HttpRequestBuilder.withAuth(player: Player) {
header("Authorization", "Bearer ${player.makeJwt()}") header("Authorization", "Bearer ${player.makeJwt("secret")}")
} }