ruby-on-rails - ruby rails : cURL DELETE token authentication

标签 ruby-on-rails ruby rest curl ruby-on-rails-4

我想为移动应用程序使用的 RoR 中的服务器做 REST API。

我的项目主要基于

http://lucatironi.github.io/tutorial/2012/10/15/ruby_rails_android_app_authentication_devise_tutorial_part_one/

并且因为在最新版本的DEVISE gem中没有token认证,所以我也是这样使用的:

https://gist.github.com/josevalim/fb706b1e933ef01e4fb6

我的问题现在出现了 - 当我使用 cURL 测试 API 时,POST(登录)是正确的,但 DELETE(注销)不起作用。我在终端中输入: p>

curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X DELETE http://localhost:3000/api/v1/sessions/\?auth_token\=CvX8WZr2MjVhWYxxEXYy

curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X DELETE http://localhost:3000/api/v1/sessions -d "{\"auth_token\":\"CvX8WZr2MjVhWYxxEXYy\"}"

(当然是我的特定 token )我得到了答案:

{"error":"You need to sign in or sign up before continuing."} with HTTP/1.1 401 Unauthorized

另外服务器日志:

Started DELETE "/api/v1/sessions" for 127.0.0.1 at 2014-06-07 03:11:17 +0200
Processing by Api::V1::SessionsController#destroy as JSON
  Parameters: {"auth_token"=>"CvX8WZr2MjVhWYxxEXYy", "session"=>{"auth_token"=>"CvX8WZr2MjVhWYxxEXYy"}}
Completed 401 Unauthorized in 1ms

我的关键文件代码:

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

    before_filter :authenticate_user_from_token!
    before_filter :authenticate_user!

    private
    def authenticate_user_from_token!
        user_email = params[:user_email].presence
        user = user_email && User.find_by_email(user_email)

        if user && Devise.secure_compare(user.authentication_token, params[:user_token])
            sign_in user, store: false
        end
    end
end

sessions_controller.rb

class Api::V1::SessionsController < Devise::SessionsController
  skip_before_filter :verify_authenticity_token,
                     :if => Proc.new { |c| c.request.format == 'application/json' }

  respond_to :json

  def create
    warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#failure")
    render :status => 200,
           :json => { :success => true,
                      :info => "Logged in",
                      :data => { :auth_token => current_user.authentication_token } }
  end

  def destroy
    warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#failure")
    current_user.update_column(:authentication_token, nil)
    render :status => 200,
           :json => { :success => true,
                      :info => "Logged out",
                      :data => {} }
  end

  def failure
    render :status => 401,
           :json => { :success => false,
                      :info => "Login Failed",
                      :data => {} }
  end
end

用户.rb

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

  attr_accessible :name, :email, :password, :password_confirmation, :remember_me

  before_save :ensure_authentication_token

  def ensure_authentication_token
      if authentication_token.blank?
          self.authentication_token = generate_authentication_token
      end
  end

  def skip_confirmation!
      self.confirmed_at = Time.now
  end

  private

  def generate_authentication_token
      loop do
          token = Devise.friendly_token
          break token unless User.where(authentication_token: token).first
      end
  end
end

routes.rb

Ihome::Application.routes.draw do
  get "welcome/index"
  devise_for :users

  root 'welcome#index'

  namespace :api do
    namespace :v1 do
      devise_scope :user do
        post 'sessions' => 'sessions#create', :as => 'login'
        delete 'sessions' => 'sessions#destroy', :as => 'logout'
      end
    end
  end
end

哪里不对,因为我分析了整个程序,找不到错误的原因?

最佳答案

我在 SimpleTokenAuthentication 的 GitHub 问题中引用了这个问题,这是一个实现 token 身份验证模式的 gem。参见 https://github.com/gonzalo-bulnes/simple_token_authentication有关 gem 的更多信息。

我最初认为您的问题与我遇到的问题相同,因为我也仅在注销操作时收到 401。但是,@gonzalo-bulnes 似乎发现了您的问题。

参见 https://github.com/gonzalo-bulnes/simple_token_authentication/issues/76#issuecomment-46836215

...isn't ukson forgetting to provide the user_email param? Token authentication can't be performed with the only auth_token. (In fact, the point of the José Valim's gist is to explain how to perform that e-mail cross-checking when implementing token authentication.)

根据我自己对您的代码的审查,他似乎是对的。尝试添加此参数,看看是否有帮助!

关于ruby-on-rails - ruby rails : cURL DELETE token authentication,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24092791/

相关文章:

ruby-on-rails - Mongoid 5.0 - Rails 4 - 收集表格 has_many

ruby-on-rails - rails 5 : How to pass collection_select values through strong_params in a fields_for?

ruby-on-rails - 在 Rspec 服务测试中包含 I18n 助手

ruby - 在 ruby 中结合正则表达式

rest - 我对 Roy Fielding 的 HTTP cookie 的 REST 替代方案的解释是否正确?

ruby-on-rails - 如何在 Rails 中异步执行 Controller.destroy 操作?

ruby - 在 block 之前更改 Sinatra 中的参数

ruby - 跳过 CSV 文件中标题前的行

http - Redis 如何适应 ASP.NET Web API OData 世界?

java - 在@POST 之后将响应从 REST 发送到 JSP