CSRF Token Test Request for Play 2.5 (Scala)

I had a little problem with my functional testing.

I have a game! 2.5 scala, in which I added CSRF validation in some forms, the associated scala -test units test, as expected, with an error:

java.lang.RuntimeException: No CSRF token present! 

I use FakeRequest with routes to check them out:

 val fakeRequest = FakeRequest(GET, s"/backOffice/login") val Some(result) = route(app, fakeRequest) 

How can I add a CRSF token to make my test successful again?

(Thanks, and sorry for the bad English, I'm not native)

+5
source share
1 answer

Update: As Howie said in his comment:

Looks like they added something similar to the game version 2.6. There you can use FakeRequest () with CSRFToken (Scala) and CSRFTokenHelper.addCSRFToken (requestBuilder) (Java), as described in the Migration Guide

For people who are still in 2.5.6, my answer still applies:

So, after looking at the Playscala classes for some time, I finally found a way to adapt this answer: fooobar.com/questions/1258783 / ... to play 2.5. 6

I even drew a line, so if someone needs it one day, here it is:

 import play.api.Application import play.api.test.FakeRequest import play.filters.csrf.CSRF.Token import play.filters.csrf.{CSRFConfigProvider, CSRFFilter} import scala.language.postfixOps trait CSRFTest { def addToken[T](fakeRequest: FakeRequest[T])(implicit app: Application) = { val csrfConfig = app.injector.instanceOf[CSRFConfigProvider].get val csrfFilter = app.injector.instanceOf[CSRFFilter] val token = csrfFilter.tokenProvider.generateToken fakeRequest.copyFakeRequest(tags = fakeRequest.tags ++ Map( Token.NameRequestTag -> csrfConfig.tokenName, Token.RequestTag -> token )).withHeaders((csrfConfig.headerName, token)) } } 

To use it, just add your test class to it, for example:

 class LoginSpec extends PlaySpec with OneAppPerSuite /* or whatever OneApp */ with CSRFTest 

then instead of calling

 val fakeRequest = FakeRequest(/* params */) 

just call

 val fakeRequest = addToken(FakeRequest(/* params */)) 

I tried to make it look like addToken {} in the controller :)

+5
source

Source: https://habr.com/ru/post/1258781/


All Articles