2

I am using Http4s library to make HTTP calls to a REST web service. the rest web service requires me to set an authentication cookie.

I have written the following code to set this cookie.

val client = PooledHttp1Client()
val uri = Uri.uri("http://localhost/restService")
val req = Request(GET, uri)
req.headers.put(`Content-Type`(MediaType.`application/json`))
val cookie = org.http4s.Cookie("foo_session", getLoginSessionId, domain = Some("localhost"), path=Some("/"))
req.headers.put(org.http4s.headers.Cookie(cookie))    
val task = client.expect[Response](req)
val list = task.run
list.response.foreach(println)
client.shutdownNow()

When I run this code I get a 401 error, meaning that the web service does not recognize that the cookie was set.

Now If I write the same code using apache http client. then everything works fine. The code below is doing exactly the same thing as above.

  val get = new HttpGet(s"http://localhost/restService")
  get.setHeader("Content-type", "application/json")
  val client = new DefaultHttpClient()
  val respHandler = new BasicResponseHandler
  val cookieStore = new BasicCookieStore()
  val cookie1 = new BasicClientCookie("foo_session", getLoginSessionId)
  cookie1.setDomain("localhost")
  cookie1.setPath("/")
  cookieStore.addCookie(cookie1)
  val localContext = new BasicHttpContext()
  localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore)
  localContext
  val responseString = client.execute(get, respHandler, cookieContext)
  val list = parse(responseString).extract[Response]
  list.response.foreach(println)
  list.response
Knows Not Much
  • 30,395
  • 60
  • 197
  • 373

2 Answers2

0

It seems that your cookie is not used into response. Did you try to use the following approach :

val cookie = org.http4s.ResponseCookie("token", su.token.getOrElse("No token"), httpOnly = true, secure = true)
Ok("resp").map(_.addCookie(cookie))
Fabszn
  • 124
  • 4
0

if you want to attach the cookie server sent to your client, you can try Cookie Jar. https://github.com/http4s/http4s/blob/main/client/src/main/scala/org/http4s/client/middleware/CookieJar.scala

Http4s strictly check the cookie from server so chance are that some cookie entries are not replied. if it is the case, you may try this one: https://github.com/chenharryhua/nanjin/blob/master/http/src/main/scala/com/github/chenharryhua/nanjin/http/client/middleware/package.scala#L39

chenhry
  • 496
  • 4
  • 7