Inject randomly generated UUID into Request using Filter


(Ben) #1

I have a filter defined:

class UUIDInjectFilter @Inject()(implicit val mat: Materializer, ec: ExecutionContext) extends Filter {

  def apply(nextFilter: RequestHeader => Future[Result])
           (requestHeader: RequestHeader): Future[Result] = {
    nextFilter(requestHeader).map { result =>
      result.withSession(requestHeader.session + ("UUID" -> randomUUID().toString))
    }

  }
}

And here is my home controller:

  def index = Action { request =>
    request.session.get("UUID").map { uuid =>
      Ok("Found UUID: " + uuid)
    }.getOrElse {
      Unauthorized("No UUID passed to action")
    }
  }

I cannot access the UUID passed from the filter to the action. I tried sessions and headers and neither work.

What am I doing wrong?


(Matthias Kurz) #2

You need to use a request attribute, not the session:
https://www.playframework.com/documentation/2.6.x/Highlights26#Request-attributes
https://www.playframework.com/documentation/2.6.x/Migration26#Request-attributes

something like nextFilter(requestHeader.addAttr(Attrs.myUUID, randomUUID())) and in the controller you can use it e.g. request.attrs.get(Attrs.myUUID). Of course you have to define Attrs.myUUID somewhere.