2
如何在功能測試中獲得CSRF令牌?它無法在會話中保存令牌並將其提交到URL中。如何在功能測試中獲得CSRF令牌
"The `send` action" should {
"return status code 400 if subject is invalid" in new WithApp with Context {
val token = CSRF.Token(42.toString)
val Some(result) = route(FakeRequest(POST, helper.CSRF(routes.ContactUs.send())(token).toString())
.withFormUrlEncodedBody(
("subject" -> "invalid"),
("name" -> "Lucky Luke"),
("email" -> "[email protected]"),
("message" -> "test")
)
.withSession(TOKEN_NAME -> token.toString)
)
status(result) must equalTo(BAD_REQUEST)
contentType(result) must beSome("application/json")
charset(result) must beSome("utf-8")
}
編輯
token.toString
不會返回令牌作爲字符串。訪問者token.value
返回可在會話中發送的適當令牌。因此,一個工作的例子是:
"The `send` action" should {
"return status code 400 if subject is invalid" in new WithApp with Context {
val token = CSRF.Token(42.toString)
val Some(result) = route(FakeRequest(POST, helper.CSRF(routes.ContactUs.send())(token).toString())
.withFormUrlEncodedBody(
("subject" -> "invalid"),
("name" -> "Lucky Luke"),
("email" -> "[email protected]"),
("message" -> "test")
)
.withSession(TOKEN_NAME -> token.value)
)
status(result) must equalTo(BAD_REQUEST)
contentType(result) must beSome("application/json")
charset(result) must beSome("utf-8")
}