I have a Scalatra 2.3 application and it uses Dispatch to contact a legacy service for some data. Some of the API calls are using cookie based auth. I would like to avoid doing login separately for every request to those secure endpoints.
My first attempt was a companion object having a var for cookie and a function getCookie. This would either return stored cookie from var or do an authentication, store received cookie to var and return it. In case of invalid cookie the logic would clear the cookie, retrieve it and retry the call.
object LegacyService {
var cookie : Option[Cookie] = None
def getCookie() : Option[Cookie] = {
this.synchronized {
if (!cookie.isDefined) {
def loginRequest = dispatch.url...
val result = (for (r <- Http(loginRequest)) yield r.getCookies).apply()
if (result.isEmpty) {
cookie = None
} else {
cookie = Some(result.get(0))
}
}
cookie
}
}
Things seemed to work fine until I was doing more than one parallel async calls requiring cookie to legacy service. For some reason this caused some kind of deadlock until app restart so with deadline ahead I ended up throwing this cookie storing code away.
Any advices how to do this properly?