These docs are for v2.0. Click to read the latest docs for v7.0.

Play provides a simple filter API for applying global filters to each request. Such a filter is basically the same as an action. It produces a request and returns a result. So it's possible to use the by Silhouette provided actions inside a filter to create a global authentication mechanism.

Following you can find a simple example which shows how you could implement a filter to restrict access to a route.

class SecuredFilter(
  implicit val env: Environment[User, SessionAuthenticator])
  extends Filter with Silhouette[User, SessionAuthenticator] {

  override def apply(next: RequestHeader => Future[Result])(
    request: RequestHeader): Future[Result] = {
    
    val action = UserAwareAction.async { r =>
      request.path match {
        case "/admin" if r.identity.isEmpty => Future.successful(Unauthorized)
        case _ => next(request)
      }
    }

    action(request).run
  }
}

To apply this filter to your application you must add it to your global object. Because of the fact that Silhouette needs some injected dependencies, it isn't possible to apply the filter with the WithFilters trait provided by Play. Instead you must override the doFilter object in your global settings.

override def doFilter(a: EssentialAction): EssentialAction = {
  import net.codingwell.scalaguice.InjectorExtensions._
  implicit val env = injector.instance[Environment[User, SessionAuthenticator]]

  Filters(super.doFilter(a), new SecuredFilter)
}