Raul Arabaolaza
Raul Arabaolaza

Reputation: 41

Intercept request and add a cookie

I would like to intercept all requests to my play backend and add a custom cookie to them. I know that the response has the withCookie method, but I am unable to find anything similar for the request. Moreover all facilities to deal with cookies in the request seem to read only, being a complete novice to Play I am stuck

I need this because we are migrating an existing webapp to a cordova based mobile app that does not allow cookies. Our authentication system is based on session cookies. I have been able to send the session id in json format and I want to send it as a header and if needed generate the session cookie on a filter or interceptor in Play so I don't need to change our authentication system in backend.

Both GlobalSettings or a Play Filter are good candidates for intercept the request, but still I don't know how to add the cookie to it. Can anybody give me a small sample or explanation of how could i do that??

Thanks!!

Upvotes: 2

Views: 805

Answers (2)

I faced the same question today and spent a lot of time trying to solve it. Here is my solution (by implementing of Request class)

  1. Usage example

val newRequest = new MockRequestImpl(request) return block(newRequest)

  1. class MockRequestImpl definition

`

class MockRequestImpl[A](req: Request[A]) extends Request[A] {
  override val connection: RemoteConnection = req.connection
  override val method: String = req.method
  override val target: RequestTarget = req.target
  override val version: String = req.version
  override val headers: Headers = req.headers
  override val attrs: TypedMap = req.attrs
  override val body: A = req.body
  // override cookies
  override def cookies = Cookies(Seq(Cookie("SessionId","00000000")))
}

`

Upvotes: 0

Raul Arabaolaza
Raul Arabaolaza

Reputation: 41

It seems I am a bit stupid.

I can easily provide all cookies I want to Play by using the Cookie http header, so no need to intercept any request here.

Sorry for the noise

Upvotes: 1

Related Questions