Testing scala Play (2.2.1) controllers with CSRF protection

前端 未结 6 982
清歌不尽
清歌不尽 2021-01-13 17:21

I\'ve been having some problems testing controllers that use Play\'s CSRF protection. To demonstrate this, I\'ve created a very simple Play application that minimally exhibi

6条回答
  •  误落风尘
    2021-01-13 17:48

    I use the following method in my base integration test class:

    def csrfRequest(method: String, uri: String)(implicit app: Application): FakeRequest[AnyContentAsEmpty.type] = {
      val tokenProvider: TokenProvider = app.injector.instanceOf[TokenProvider]
      val csrfTags = Map(Token.NameRequestTag -> "csrfToken", Token.RequestTag -> tokenProvider.generateToken)
      FakeRequest(method, uri, FakeHeaders(), AnyContentAsEmpty, tags = csrfTags)
    }
    

    Then you can use it in your tests where you would use FakeRequest.

提交回复
热议问题