2

I am new to Play Framework, and I wanted to implement an interceptor or a filter that gets executed before the request goes to the Action class.

I wanted an interceptor/filter that to return HTTP error (e.g. 401), if a certain header variable is not present.

I did some googling, and I found out about the Filter (play.api.mvc.Filter) object, but the implementation returns mvc.Result, instead of Response.

override def apply(next: (mvc.RequestHeader) => Future[mvc.Result])(request: mvc.RequestHeader)

Another solution that I can think of is to create a customized Action by extending ActionBuilder, but I'd rather not do that, If I can design a catch all functionality like Filter.

Any help will be greatly appreciated. Thank you.

2 Answers 2

6

For future reference. This is the implementation of the filter. Thanks to tryx for the help.

import play.api.mvc
import play.api.mvc.{RequestHeader, Filter}
import play.api.mvc.Results._
import scala.concurrent.ExecutionContext.Implicits.global

class AuthorizedFilter(requestHeader: RequestHeader) extends Filter {



  private def authorizationRequired(request: mvc.RequestHeader) = {

    request.headers.get("Authorized").
      map( authorizedValue => authorizedValue.eq("ABCDEFG")).
      getOrElse(false)

  }


  override def apply(next: (mvc.RequestHeader) => Future[mvc.Result])(request: mvc.RequestHeader) =  {
      if(authorizationRequired(request)) {

        println("YOU are authorized!!")

        next(request)

      }
      println("NOT AUTHORIZED!")
      Future {Unauthorized }
    }
}

Create a Filter object in the root level of the application. (/app).

import javax.inject.Inject

import play.api.http.HttpFilters

class Filters @Inject() (authorizedFilter: AuthorizedFilter) extends HttpFilters {

  def filters = Seq(authorizedFilter)
}
1

In your filter you have 2 options, you can either call next which passes control to the next filter or you can return a Future[Result] explicitly which terminates the chain. If you call next, eventually the filter chain will end and it will reach the action.

It sounds like you want a filter with an apply method like

apply(next: RequestHeader => Future[Result])(request: RequestHeader): Future[SimpleResult] = {
  if (headersok){
    next(request)
  } else {
    Future{ Unauthorized }
  }

}

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.