Api :: V1 :: UsersController #create中的ActionController InvalidAuthenticityToken

时间:2017-01-12 17:14:14

标签: android ruby-on-rails ruby

我将使用Ruby on Rails创建restful API。我想创建,删除,显示和更新数据。所有这些都必须是JSON才能在Android设备中获得它。我也在使用Postman检查我的API。 这就是我所做的:

我的控制器:

class Api::V1::UsersController < ApplicationController
    respond_to :json

    def show
        respond_with User.find(params[:id])
    end

    def create
        user=User.new(user_params)
        if user.save
            render json: user, status: 201
        else
            render json: {errors: user.errors}, status: 422
        end
    end

    def update
        user=User.find(params[:id])
        if user.update(user_params)
            render json: user, status:200
        else
        render json: {erros: user.errors},status: 422
        end

    end

    def destroy
        user=User.find(params[:id])
        user.destroy
        head 204
    end

    private
    def user_params
        params.require(:user).permit(:email,:password,:password_confirmation)
    end
end

这是我的路线档案:

Rails.application.routes.draw do
  devise_for :users
  namespace :api, defaults:{ format: :json } do
    namespace :v1 do
    resources :users, :only=>[:show,:create,:update,:destroy]   
    end
  end
end

并将以下代码添加到我的Gemfile中:

gem "devise"
gem 'active_model_serializers'

我不知道为什么当我想通过邮递员创建时,我收到以下错误:

ActionController InvalidAuthenticityToken in Api::V1::UsersController#create

2 个答案:

答案 0 :(得分:6)

您需要在application_controller.rb中进行以下更改

更改

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
end

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :null_session
end

修改

更好的方法是跳过特定控制器的身份验证

class Api::V1::UsersController < ApplicationController
  skip_before_action :verify_authenticity_token

  respond_to :json
  # ...
end

答案 1 :(得分:0)

在application_controller.rb

对于 Web控制器

protect_from_forgery with: :exception

对于 API控制器

protect_from_forgery with: :null_session

您还可以使用 prepend 参数选择何时运行此验证(此选项的默认值为false)

protect_from_forgery with: :null_session, prepend: true

就像文档中所说的

  

如果希望伪造保护依赖于其他回调,例如身份验证方法(Oauth与Cookie身份验证),这很有用