How to generate CSRF token in Reactjs and send to Play Framework?

六眼飞鱼酱① 提交于 2020-01-04 02:52:33

问题


I was trying to send a post request from react form to play framework. It is throwing the following error:

Caused by: java.lang.RuntimeException: No CSRF token was generated for this request! Is the CSRF filter installed?

While using Play templates, CSRF token is handled from the template itself. Since I'm trying to use React for front end, I cannot use Play templates. Can anyone guide me on generating CSRF token in React and passing it to Play?

Thanks in advance


回答1:


It looks like you can set up an action to generate a CSRF token (see docs):

If you are not using the CSRF filter, you also should inject the CSRFAddToken and CSRFCheck action wrappers to force adding a token or a CSRF check on a specific action. Otherwise the token will not be available.

import play.api.mvc._
import play.api.mvc.Results._
import play.filters.csrf._
import play.filters.csrf.CSRF.Token

class CSRFController(components: ControllerComponents, addToken: CSRFAddToken, checkToken: CSRFCheck) extends AbstractController(components) {
  def getToken = addToken(Action { implicit request =>
    val Token(name, value) = CSRF.getToken.get
    Ok(s"$name=$value")
  })
}

GET this and pass it to the React form:

<input type="hidden" name="csrfToken" value="1234567890abcdef"/>

(or add it directly to the POST request.)



来源:https://stackoverflow.com/questions/50713068/how-to-generate-csrf-token-in-reactjs-and-send-to-play-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!