如何测试基于令牌的身份验证?

时间:2014-07-15 16:31:14

标签: ruby-on-rails rspec

我需要一些帮助来测试以下内容。我正在做关于保护api的RailsCast:http://railscasts.com/episodes/352-securing-an-api?view=asciicast

我有RequestController before_filter来检查请求是否有令牌:

class RequestsController < ApplicationController
  include ActionController::MimeResponds
  include ActionController::HttpAuthentication::Token::ControllerMethods

  before_filter :restrict_access
  respond_to :json

#...

def authenticate
    return restrict_access
  end

  private
  def restrict_access
    authenticate_or_request_with_http_token do |token, options|
      ApiKey.exists?(access_token: token)
    end
  end

end

我的失败的rspec测试看起来像:

it 'responds successfully to generic request because of key protection' do
    api_key = ApiKey.create
    api_key.save!

    get :index
    request.headers["token"] = api_key.access_token
    expect(response).to be_success # test for the 200 status-code
end

结果:expected success? to return true, got false

我不明白如何将有效的api_key注入到请求中,以便响应评估为true。有任何想法吗?感谢。

1 个答案:

答案 0 :(得分:8)

令牌身份验证需要此格式的HTTP_AUTHORIZATION标头:

Token token="my-api-token"

此外,您还要在get :index行之前设置标题:

request.headers["HTTP_AUTHORIZATION"] = "Token token=\"#{api_key.access_token}\""
get :index

如果您愿意,可以使用encode_credentials方法:

request.headers["HTTP_AUTHORIZATION"] = ActionController::HttpAuthentication::Token.encode_credentials(api_key.access_token)