加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何测试基于令牌的身份验证?

发布时间:2020-12-17 03:41:19 所属栏目:百科 来源:网络整理
导读:测试以下内容需要一些帮助.我正在做关于保护api的RailsCast: http://railscasts.com/episodes/352-securing-an-api?view=asciicast 我有一个带有before_filter的RequestController来检查请求是否有令牌: class RequestsController ApplicationController i
测试以下内容需要一些帮助.我正在做关于保护api的RailsCast: http://railscasts.com/episodes/352-securing-an-api?view=asciicast

我有一个带有before_filter的RequestController来检查请求是否有令牌:

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

结果:预期成功?回归真实,变得虚伪

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

解决方法

令牌认证需要以这种格式的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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读