【问题标题】:Authorization Token in request header for Rails JSON API DELETE not being recognisedRails JSON API DELETE 的请求标头中的授权令牌未被识别
【发布时间】:2015-02-12 15:00:51
【问题描述】:

我正在使用 rails-api 组合一个 Restful JSON API。

我正在使用 rspec 测试我的 DELETE api/v1/users/:id。当我使用 HTTP 令牌作为身份验证(用于删除操作)时,我无法让它通过。我已经通过终端进行了测试,它可以工作,但测试不会通过。

这里是测试规范/requests/api/v1/users_spec.rb

describe "DELETE api/v1/users/:id" do
it "deletes the requested user" do
  user = FactoryGirl.create(:user)
  request_headers = {
    'Authorization' => 'Token token="foobar"'
  }

  delete "api/v1/users/#{user.id}", request_headers

  expect(response.status).to eq 204
 end
end

我得到的错误是expect 204 got 401.

在我的 users_controller.rb 中,我使用它来获取令牌

before_action :authenticate, only: [ :destroy ]
TOKEN = "foobar"

def destroy
   @user = find_user
   @user.destroy
   head 204
end

private

def authenticate
  authenticate_or_request_with_http_token do |token, options|
    token == TOKEN
  end
end

我还尝试了以下方法在 request_headers 中设置授权令牌

request_headers = {
    'HTTP_AUTHORIZATION' => 'Token token="foobar"'
  }

谁能指出我哪里出错或指出我正确的方向?

【问题讨论】:

    标签: ruby-on-rails json http-headers rails-api


    【解决方案1】:

    现在通过这种方法解决了这个问题:

    describe "DELETE api/v1/users/:id" do
    let(:auth_headers) {
       { 'AUTHORIZATION' => 'Token token="foobar"' }
     }
    let(:user) { FactoryGirl.create(:user) }
    
      it "deletes the requested user" do
    
        delete "api/v1/users/#{user.id}", {}, auth_headers
    
        expect(response.status).to eq 204
      end
    end
    

    基本上http头需要在第三个参数中设置。上面的解决方案将它作为第二个传递,因此它没有被识别。

    【讨论】:

      猜你喜欢
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-26
      • 1970-01-01
      • 1970-01-01
      • 2013-09-03
      • 2015-11-27
      相关资源
      最近更新 更多