alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Play Framework/Scala example source code file (CSRFFilterSpec.scala)

This example Play Framework source code file (CSRFFilterSpec.scala) is included in my "Source Code Warehouse" project. The intent of this project is to help you more easily find Play Framework (and Scala) source code examples by using tags.

All credit for the original source code belongs to Play Framework; I'm just trying to make examples easier to find. (For my Scala work, see my Scala examples and tutorials.)

Play Framework tags/keywords

api, concurrent, csrffilter, csrftester, future, get, html, lib, library, not_found, ok, play, play framework, string, wsrequestholder, wsresponse

The CSRFFilterSpec.scala Play Framework example source code

/*
 * Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com>
 */
package play.filters.csrf

import scala.concurrent.Future
import play.api.libs.ws._
import play.api.mvc._
import play.api.libs.json.Json
import play.api.test._
import scala.util.Random
import play.api.libs.Crypto

/**
 * Specs for the global CSRF filter
 */
object CSRFFilterSpec extends CSRFCommonSpecs {

  sequential

  import CSRFConf._

  "a CSRF filter also" should {

    // conditions for adding a token
    "not add a token to non GET requests" in {
      buildCsrfAddToken()(_.put(""))(_.status must_== NOT_FOUND)
    }
    "not add a token to GET requests that don't accept HTML" in {
      buildCsrfAddToken()(_.withHeaders(ACCEPT -> "application/json").get())(_.status must_== NOT_FOUND)
    }
    "add a token to GET requests that accept HTML" in {
      buildCsrfAddToken()(_.withHeaders(ACCEPT -> "text/html").get())(_.status must_== OK)
    }
    "not add a token to HEAD requests that don't accept HTML" in {
      buildCsrfAddToken()(_.withHeaders(ACCEPT -> "application/json").head())(_.status must_== NOT_FOUND)
    }
    "add a token to HEAD requests that accept HTML" in {
      buildCsrfAddToken()(_.withHeaders(ACCEPT -> "text/html").head())(_.status must_== OK)
    }

    // extra conditions for not doing a check
    "not check non form bodies" in {
      buildCsrfCheckRequest(false)(_.post(Json.obj("foo" -> "bar")))(_.status must_== OK)
    }
    "not check safe methods" in {
      buildCsrfCheckRequest(false)(_.put(Map("foo" -> "bar")))(_.status must_== OK)
    }

    // other
    "feed the body once a check has been done and passes" in {
      withServer(Nil) {
        case _ => CSRFFilter()(Action(
          _.body.asFormUrlEncoded
            .flatMap(_.get("foo"))
            .flatMap(_.headOption)
            .map(Results.Ok(_))
            .getOrElse(Results.NotFound)))
      } {
        val token = Crypto.generateSignedToken
        import play.api.Play.current
        await(WS.url("http://localhost:" + testServerPort).withSession(TokenName -> token)
          .post(Map("foo" -> "bar", TokenName -> token))).body must_== "bar"
      }
    }

    val notBufferedFakeApp = FakeApplication(
      additionalConfiguration = Map("application.secret" -> "foobar", "csrf.body.bufferSize" -> "200"),
      withRoutes = {
        case _ => CSRFFilter()(Action(
          _.body.asFormUrlEncoded
            .flatMap(_.get("foo"))
            .flatMap(_.headOption)
            .map(Results.Ok(_))
            .getOrElse(Results.NotFound)))
      }
    )

    "feed a not fully buffered body once a check has been done and passes" in new WithServer(notBufferedFakeApp, testServerPort) {
      val token = Crypto.generateSignedToken
      val response = await(WS.url("http://localhost:" + port).withSession(TokenName -> token)
        .withHeaders(CONTENT_TYPE -> "application/x-www-form-urlencoded")
        .post(
          Seq(
            // Ensure token is first so that it makes it into the buffered part
            TokenName -> token,
            // This value must go over the edge of csrf.body.bufferSize
            "longvalue" -> Random.alphanumeric.take(1024).mkString(""),
            "foo" -> "bar"
          ).map(f => f._1 + "=" + f._2).mkString("&")
        )
      )
      response.status must_== OK
      response.body must_== "bar"
    }

    "be possible to instantiate when there is no running application" in {
      CSRFFilter() must beAnInstanceOf[AnyRef]
    }

    "work with a Java error handler" in {
      def csrfCheckRequest = buildCsrfCheckRequestWithJavaHandler()
      def csrfAddToken = buildCsrfAddToken("csrf.cookie.name" -> "csrf")
      def generate = Crypto.generateSignedToken
      def addToken(req: WSRequestHolder, token: String) = req.withCookies("csrf" -> token)
      def getToken(response: WSResponse) = response.cookies.find(_.name.exists(_ == "csrf")).flatMap(_.value)
      def compareTokens(a: String, b: String) = Crypto.compareSignedTokens(a, b) must beTrue

      sharedTests(csrfCheckRequest, csrfAddToken, generate, addToken, getToken, compareTokens, UNAUTHORIZED)
    }

  }


  def buildCsrfCheckRequest(sendUnauthorizedResult: Boolean, configuration: (String, String)*) = new CsrfTester {
    def apply[T](makeRequest: (WSRequestHolder) => Future[WSResponse])(handleResponse: (WSResponse) => T) = withServer(configuration) {
      case _ => if (sendUnauthorizedResult) {
        CSRFFilter(errorHandler = new CustomErrorHandler())(Action(Results.Ok))
      } else {
        CSRFFilter()(Action(Results.Ok))
      }
    } {
      import play.api.Play.current
      handleResponse(await(makeRequest(WS.url("http://localhost:" + testServerPort))))
    }
  }

  def buildCsrfCheckRequestWithJavaHandler() = new CsrfTester {
    def apply[T](makeRequest: (WSRequestHolder) => Future[WSResponse])(handleResponse: (WSResponse) => T) = {
      withServer(Seq(
        "csrf.cookie.name" -> "csrf",
        "csrf.error.handler" -> "play.filters.csrf.JavaErrorHandler"
      )) {
        case _ => new CSRFFilter().apply(Action(Results.Ok))
      } {
        import play.api.Play.current
        handleResponse(await(makeRequest(WS.url("http://localhost:" + testServerPort))))
      }
    }
  }


  def buildCsrfAddToken(configuration: (String, String)*) = new CsrfTester {
    def apply[T](makeRequest: (WSRequestHolder) => Future[WSResponse])(handleResponse: (WSResponse) => T) = withServer(configuration) {
      case _ => CSRFFilter()(Action { implicit req =>
        CSRF.getToken(req).map { token =>
          Results.Ok(token.value)
        } getOrElse Results.NotFound
      })
    } {
      import play.api.Play.current
      handleResponse(await(makeRequest(WS.url("http://localhost:" + testServerPort))))
    }
  }

  class CustomErrorHandler extends CSRF.ErrorHandler {
    import play.api.mvc.Results.Unauthorized
    def handle(req: RequestHeader, msg: String) = Unauthorized(msg)
  }
}

class JavaErrorHandler extends CSRFErrorHandler {
  def handle(msg: String) = play.mvc.Results.unauthorized()
}

Other Play Framework source code examples

Here is a short list of links related to this Play Framework CSRFFilterSpec.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.