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

Joe*_*sey 4 rspec ruby-on-rails

测试以下内容需要一些帮助.我正在做关于保护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
Run Code Online (Sandbox Code Playgroud)

我失败的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
Run Code Online (Sandbox Code Playgroud)

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

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

Dyl*_*kow 8

令牌认证需要HTTP_AUTHORIZATION这种格式的标头:

Token token="my-api-token"
Run Code Online (Sandbox Code Playgroud)

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

request.headers["HTTP_AUTHORIZATION"] = "Token token=\"#{api_key.access_token}\""
get :index
Run Code Online (Sandbox Code Playgroud)

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

request.headers["HTTP_AUTHORIZATION"] = ActionController::HttpAuthentication::Token.encode_credentials(api_key.access_token)
Run Code Online (Sandbox Code Playgroud)