Skip to content

Instantly share code, notes, and snippets.

@domdorn
Last active February 14, 2020 10:09
Show Gist options
  • Save domdorn/9a3490edd9f7ea7e91eed07b79dad0e3 to your computer and use it in GitHub Desktop.
Save domdorn/9a3490edd9f7ea7e91eed07b79dad0e3 to your computer and use it in GitHub Desktop.
PlayFramework 2.5: Global CSRF Protection – Disable CSRF selectively
play.filters.csrf.header.bypassHeaders {
Csrf-Token = "my-secret-csrf-off-switch"
}
play.http.filters=framework.Filters
package framework
import javax.inject.Inject
import play.api.http.HttpFilters
import play.filters.csrf.RouteCommentExcludingCSRFFilterFacade
import play.filters.gzip.GzipFilter
class Filters @Inject()(
routeCommentExcludingCSRFFilterFacade: RouteCommentExcludingCSRFFilterFacade,
gzipFilter: GzipFilter
) extends HttpFilters {
val _filters = Seq(metricsFilter,
gzipFilter,
routeCommentExcludingCSRFFilterFacade
)
override def filters = _filters
}
package play.filters.csrf
import javax.inject.Inject
import play.api.mvc.{EssentialAction, EssentialFilter}
import scala.concurrent.ExecutionContext
class RouteCommentExcludingCSRFFilterFacade @Inject()(filter: CSRFFilter)(implicit ec: ExecutionContext) extends EssentialFilter {
override def apply(nextFilter: EssentialAction): EssentialAction = new EssentialAction {
import play.api.mvc._
override def apply(rh: RequestHeader) = {
if (rh.tags.getOrElse("ROUTE_COMMENTS", "").contains("NOCSRF")) {
// this is required for GET/HEAD requests with no prior HTTP-Request (like bingbot)
// so they are missing a context.
// if the rendering template is using the CSRF-token to render a form, it would blow
// up if we're not processing it through the CSRF filter
val copy: RequestHeader = rh.copy(headers = rh.headers.add(("Csrf-Token", "my-secret-csrf-off-switch")))
filter.apply(nextFilter)(copy)
} else {
filter.apply(nextFilter)(rh)
}
}
}
}
#NOCSRF
POST /search @controllers.SearchController.search()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment