ruby-on-railspostauthenticity-token

Rails POST Request Invalid Token Authority


I have built a POST request route as:

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

with action:

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

That should return a JSON object of the users that match. I have tested with POSTMAN as:

enter image description here

But what returns is the error noting invalid authenticity token

How can I reconfigure to make this POST route work?


Solution

  • By default Rails uses CSRF protection in controller. It is add to your form hidden_field with authenticity token. But in your case you do not use form you can disable CSRF protection on controller by skipping the verification before_action. Add to top of your requests controller:

    skip_before_filter :verify_authenticity_token
    

    or in Rails 4 and 5(it is the same command):

    skip_before_action :verify_authenticity_token