Bùi Văn Dương
Bùi Văn Dương

Reputation: 63

Can't verify CSRF token authenticity! RAILS API with POST

I trying post a json file with Rails API. I have try to fix but can't run This my problem:

Sever log:

Started POST "/students/" for 127.0.0.1 at 2016-09-17 17:45:33 +0700
  ActiveRecord::SchemaMigration Load (0.0ms)  SELECT "schema_migrations".* FROM "schema_migrations"
Processing by Devise::RegistrationsController#create as */*
  Parameters: {"student"=>{"name"=>"Duong", "score"=>"10"}, "registration"=>{"student"=>{"name"=>"Duong", "score"=>"10"}}}
Can't verify CSRF token authenticity.
Unpermitted parameters: name, score
   (0.0ms)  begin transaction
   (0.0ms)  rollback transaction
  Rendering C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/devise-4.2.0/app/views/devise/registrations/new.html.erb within layouts/application
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/devise-4.2.0/app/views/devise/shared/_links.html.erb (10.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/devise-4.2.0/app/views/devise/registrations/new.html.erb within layouts/application (60.0ms)
Completed 500 Internal Server Error in 442ms (ActiveRecord: 0.0ms)

Student.rb

This is my student model

class Student < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

Application_controller

I have fix excetion => null_session

class ApplicationController < ActionController::Base

  protect_from_forgery with: :null_session

end

Student_controller

class Api::StudentsController < ApplicationController
  def index
    students = Student.all
    render json: students, status: 200
  end
  def show
    response_with Student.find(params[:id])
  end
  def create
    student = Student.new(student_params)
    #if you save successfully than response with json data and status code 201
    if student.save
      render json: user, status: 201, location: student
    else
      render json: {error: user.errors}, status: 422
    end
  end
  private
  def student_params
    params.require(:student).permit(:name, :score)
  end
end

router.rb

Rails.application.routes.draw do
  devise_for :students
  namespace :api, path: '/',constraints: {subdomain: 'api'} do
    resources :students, only: [:index, :show, :create]
  end
end

But, when I send a post to api.1312100.com/students/

{"student": {"name": "Duong", "score": "10"}}

have a error:

500 internal server error

Upvotes: 5

Views: 14245

Answers (3)

Milind
Milind

Reputation: 5112

It worked for me. So ideally, you need to add skip_before_action :verify_authenticity_token at every controller that is using json format, rather than adding it into the base_controller or application_controller, else it won't work.

Initially I too added into the api/v1/base_controller.rb but still it was showing the same error of Can't verify CSRF token authenticity., then I experimented and added in two of my api/v1/sessions and api/v1/registrations controller and then it worked.

I am using Rails 7 with Ruby 3.

Upvotes: 0

Tejas
Tejas

Reputation: 186

In Api::StudentsController add:

skip_before_action :verify_authenticity_token

Upvotes: 6

7urkm3n
7urkm3n

Reputation: 6311

Curling:

curl -i -H "Accept: application/json" -H "Content-type:application/json" -X POST -d '{"student": {"name": "Duong", "score": "10"}}' http://api.1312100.com/students/

Application Controller

class ApplicationController < ActionController::Base
    protect_from_forgery with: :exception, if: Proc.new { |c| c.request.format != 'application/json' }
    protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }
end

Upvotes: 7

Related Questions