Antoni Zwolski
02/16/2024, 2:25 PMfun sendEvent(event: Event) {
sendEventGeneric(endpoint, event).apply {
logger.infov("${event.type} event sent to $endpoint")
}
}
fun sendAdminEvent(event: AdminEvent) {
sendEventGeneric(adminEndpoint, event).apply {
logger.infov("Admin event sent to $adminEndpoint")
}
}
private fun sendEventGeneric(url: String, event: Any) {
val eventData = gson.toJson(event)
try {
val httpEntity: HttpEntity = ByteArrayEntity(eventData.toString().toByteArray())
val httpPost = HttpPost(url)
httpPost.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE)
httpPost.setHeader("Content-Type", "application/json")
httpPost.entity = httpEntity
val response = HttpTools.executeCall(client, httpPost)
HttpTools.stopOnError(response)
logger.infov("Response: ", response.responseAsJsonObject)
return
} catch (e: Exception) {
logger.error("Error while sending event: ${e.message}", e)
throw e
}
}
Server side:
fun Route.authRoutes(userApi: UserApi) {
post<AuthEventDto>("/register") { authEventDto ->
val offersResponse = userApi.saveUser(authEventDto)
call.respondSuccess(data = offersResponse)
}
post<AuthEventDto>("/login") { authEventDto ->
val offersResponse = userApi.updateUser(authEventDto)
call.respondSuccess(data = offersResponse)
}
}Júlio Santos
02/16/2024, 8:43 PMkotlin
fun Route.authRoutes(userApi: UserApi, secretKey: String) {
post<AuthEventDto>("/register") { authEventDto ->
val authHeader = call.request.headers["Authorization"]
if (authHeader != secretKey) {
call.respond(HttpStatusCode.Unauthorized, "Invalid secret key")
return@post
}
val offersResponse = userApi.saveUser(authEventDto)
call.respondSuccess(data = offersResponse)
}
post<AuthEventDto>("/login") { authEventDto ->
val authHeader = call.request.headers["Authorization"]
if (authHeader != secretKey) {
call.respond(HttpStatusCode.Unauthorized, "Invalid secret key")
return@post
}
val offersResponse = userApi.updateUser(authEventDto)
call.respondSuccess(data = offersResponse)
}
}
In this example, the Authorization header is expected to contain the shared secret key. If it doesn't match the secretKey expected by the server, the request is rejected with an Unauthorized status code.
Remember to keep the secretKey secure and not hard-coded in your source code. It should be stored in a secure configuration store or environment variable.
For a more robust solution, you might consider implementing OAuth 2.0 client credentials grant between Keycloak and your server, where your server acts as an OAuth 2.0 resource server. This is more complex to set up but provides a standard and secure method for machine-to-machine authentication.Aleksei Tirman [JB]
02/19/2024, 8:06 AM