如何在功能测试中获取 CSRF Token?在会话中保存令牌并在 URL 中提交它是行不通的。
"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" -> "test@test.com"),
("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" -> "test@test.com"),
("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")
}