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
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.)