Rails POST请求无效的令牌权限

时间:2015-03-29 18:33:46

标签: ruby-on-rails post authenticity-token

我已经构建了一个POST请求路由:

match '/getActivatedFriends',
  to: 'requests#getActivatedFriends', via: 'post',
  constraints: { friends_phone_number_csv: /([0-9]+,?)+/ } 

采取行动:

def getActivatedFriends
    @results = BusinessUser.find_by_sql("SELECT 
                                            a.id
                                         ,  a.username
                                         ,  a.phoneNumber
                                         FROM users a
                                         WHERE phoneNumber in ('+params[:friends_phone_number_csv]+') and
                                               removed = 0 and
                                               is_user = 1;")

    respond_to do |format|
        format.html
        format.json { render json: { friends_match: @results }}
    end         
end

那应该返回匹配的用户的JSON对象。我用POSTMAN测试过:

enter image description here

但是返回的是错误,注意到无效的真实性令牌

如何重新配置​​以使此POST路由有效?

1 个答案:

答案 0 :(得分:5)

默认情况下,Rails在控制器中使用CSRF protectionIt is add to your form hidden_field with authenticity token.但在你的情况下,你不使用表格 您可以通过跳过验证before_action来禁用控制器上的CSRF protection。 添加到请求控制器的顶部:

skip_before_filter :verify_authenticity_token

Rails 4 and 5(这是同一个命令):

skip_before_action :verify_authenticity_token
相关问题