ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):将 JSON 参数发送到 Rails 控制器时

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken): While POSTing a JSON arugments to a Rails Controller

我正在使用 React/Redux 前端和 rails 服务器 运行 后端。我有一个按钮,onClick 将发送触发一个动作,该动作由两个分派和一个提取组成,一个分派之前和一个之后。提取正确地找到了服务器,但我得到了 422 错误,这意味着在接受请求后 Rails 方面存在一些问题。错误如您在标题中所见,ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken)。但是,我将参数设置为 require a player object 和 permit 适当的属性。 获取操作(我知道它有效)看起来像这样

export default function completeAttributeSelection(playerObj){
    const playerPOST = ({
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Accept": "application/json"
        },
        body: JSON.stringify({
            atk: playerObj.atk,
            sAtk: playerObj.sAtk,
            def: playerObj.def,
            sDef: playerObj.sDef,
            spd: playerObj.spd,
            hp: playerObj.hp,
            name: playerObj.name
        })
    })
    return (dispatch) => {
        dispatch({type: "LOADING"})
        console.log("Domain: " + DOMAIN())
        fetch((DOMAIN() + "/players/update_or_create"), playerPOST)
            .then(resp => resp.json())
            .then(json => {
                console.log(json)
                dispatch({type: "ATTRIBUTE_UPDATE_COMPLETE", payload: json})
            })
    }
}

这是处理请求的控制器:

class PlayersController < ApplicationController

    def update_or_create
        puts ("Update or Create hit")
        @player = Player.create_or_find_by(name: player_params[:name])
        puts (player_params)
        @player.update(class: player_params[:class], lvl: player_params[:level], atk: player_params[:atk], sAtk: player_params[:sAtk], def: player_params[:def], sDef: player_params[:sDef], spd: player_params[:spd], hp: player_params[:hp])
        render json{@player}
    end

    private
    def player_params
        params.require(:player).permit(:name, :inv_hash, :lvl, :name, :class, :atk, :def, :sAtk, :sDef, :spd, :hp, :move_distance)
    end
end

因为我没有使用任何秘密、密钥或任何类似的东西 has_secure_password,所以我正在努力了解到底是什么被这个问题所困扰。 我从 Rails 终端(在长期混乱的错误之前)得到的全部提示如下...

Processing by PlayersController#update_or_create as JSON
  Parameters: {"atk"=>6, "sAtk"=>6, "def"=>5, "sDef"=>9, "spd"=>10, "hp"=>85, "name"=>"test01", "player"=>{"name"=>"test01", "atk"=>6, "def"=>5, "sAtk"=>6, "sDef"=>9, "spd"=>10, "hp"=>85}}
HTTP Origin header (http://localhost:3000) didn't match request.base_url (http://localhost:3006)
Completed 422 Unprocessable Entity in 0ms (ActiveRecord: 0.3ms | Allocations: 394)


  
ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):

使它起作用的简短答案是将 protect_from_forgery with: :null_session 添加到您的控制器。

class PlayersController < ApplicationController
  protect_from_forgery with: :null_session

  # ...
end

较长的答案涉及 CSRF 和所谓的真实性令牌。这似乎是一个很好的来源 https://blog.nvisium.com/understanding-protectfromforgery

Cross-Site Request Forgery is a serious vulnerability that stems from the trust that web applications place on the session identification cookies that are being passed between browser and server. For a more detailed explanation of CSRF, I suggest looking at the OWASP guide on Cross-Site Request Forgery.

Rails includes a built-in mechanism for preventing CSRF, protect_from_forgery, which is included by default in the application_controller.rb controller when generating new applications. This protect_from_forgery method leverages magic to ensure that your application is protected from hackers!