scalacookiesheadercompositionlagom

Lagom - Add header to response in service call composition


i want to write code which will refresh cookie (via set-cookie http header) in Lagom.
For clarification Cookie is an encoded string (for example AES).
Lets take lagom service call composition for authentication from Implementing services and edit it

def authenticated[Request, Response](
    serviceCall: User => ServerServiceCall[Request, Response]
) = ServerServiceCall.composeAsync { requestHeader =>
  
  //Get cookie from header and decode it
  val cookie = decodeCookie(requestHeader) 
 
  //Get user based on cookie decode function  
  val userLookup = getUser(cookie)

  userLookup.map {
    case Some(user) =>
        serviceCall(user)

    case None => throw Forbidden("User must be authenticated")
  }
}

It is possible to manipulate serviceCall(user) response headers?

I tried something like this:

serviceCall( employee ).handleResponseHeader { case (responseHeader, response) =>
    responseHeader.withHeader("Set-Cookie",encodeCookie("NewCookieStringExample")) // Add header
    response
}

But function handleResponseHeader requires only response[T] as result and header would not be changed because is immutable.

I know that i can pass cookie to serviceCall(user) and in every service call implementation return tuple with ResponseHeader and Response but this will impact all endpoints and will add much more code.

Use of HeaderFilter is possible too but this would decode and encode cookie twice in one request (in header filter and in authenticated service call composition )

Any tips?


Solution

  • You can return the modified Header and the Response as a Tuple:

    serviceCall( employee ).handleResponseHeader((responseHeader, response) => {
         val modifiedHeader =  responseHeader.withHeader("Set-Cookie",encodeCookie("NewCookieStringExample")) // Add header
        (modifiedHeader, response)
    })
    

    By the way, The provided example does not compile for me. composeAsync wants a Future[ServerServiceCall[...]].