我需要一些帮助来测试以下内容。我正在做关于保护 api 的 RailsCast:http://railscasts.com/episodes/352-securing-an-api?view=asciicast
我有一个 RequestController
与 before_filter
检查请求是否有 token :
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 注入(inject)请求中,以便响应评估为真。有任何想法吗?谢谢。
最佳答案
token 身份验证需要 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)
关于ruby-on-rails - 如何测试基于 token 的身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24763505/