如何在Reactjs中生成CSRF令牌并将其发送到Play框架? [英] How to generate CSRF token in Reactjs and send to Play Framework?

查看:75
本文介绍了如何在Reactjs中生成CSRF令牌并将其发送到Play框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从react表单发送发布请求以播放框架.它引发以下错误:

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?

使用Play模板时,CSRF令牌是从模板本身处理的.由于我正在尝试将React用于前端,因此无法使用Play模板.谁能指导我在React中生成CSRF令牌并将其传递给Play?

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?

预先感谢

推荐答案

您似乎可以设置一个操作来生成CSRF令牌(请参见

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

如果不使用CSRF筛选器,则还应该注入CSRFAddToken和CSRFCheck操作包装,以强制在特定操作上添加令牌或CSRF检查.否则,令牌将不可用.

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")
  })
}

获取此内容并将其传递给React表单:

GET this and pass it to the React form:

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

(或直接将其添加到POST请求中.)

(or add it directly to the POST request.)

这篇关于如何在Reactjs中生成CSRF令牌并将其发送到Play框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆