如何将auth令牌添加到每个http RSpec测试头

时间:2017-12-30 06:55:23

标签: ruby-on-rails ruby rspec http-headers

我在尝试验证请求规范时遇到问题。如何在每个http请求的标头中传递有效的身份验证令牌?我的方法是否正确?

tweets_request_spec.rb

require 'rails_helper'

RSpec.describe 'Tweets API', type: :request do
  before do
    @tweets = create_list(:tweet, 10)
    @tweet = @tweets.first
  end

  describe 'GET /tweets' do
    before { get '/tweets', { "Authorization": *some sort of token*} }

    it "returns tweets" do
      expect(json).to_not be_empty
      expect(json).to eq(10)
    end

    it "is a successful http request" do
      expect(response).to have_http_response(200)
    end
  end
end

以下是我的身份验证控制器代码,以及帮助生成和解码在http标头中传递的身份验证令牌的模块。

authentication_controller.rb

class AuthenticationController < ApplicationController
  skip_before_action :authenticate_request

  def authenticate
    command = AuthenticateUser.call(params[:email], params[:password])

    if command.success?
      render json: { auth_token: command.result }
    else
      render json: { error: command.errors }, status: :authorized
    end
  end
end

authorize_api_request.rb

class AuthorizeApiRequest
  prepend SimpleCommand

  def initialize(headers = {})
    @headers = headers
  end

  def call
    user
  end

  private

  attr_reader :headers

  def user
    @user ||= User.find(decoded_auth_token[:user_id]) if decoded_auth_token
    @user ||= errors.add(:token, 'Invalid token') && nil
  end

  #decode the auth token and retrieve the user id
  def decoded_auth_token
    @decoded_auth_token ||= JSONWebToken.decode(http_auth_header)
  end

  #retrieve auth token from header
  def http_auth_header
    if headers['Authorization'].present? 
      return headers['Authorization'].split(' ').last
    else
      errors.add(:token, 'Missing token')
    end
  end
end

1 个答案:

答案 0 :(得分:3)

the official pluralsight page

复制的部分代码提取

要进行身份验证的端点位于config/routes.rb

post 'authenticate', to: 'authentication#authenticate'

执行此操作。如果您正确进行身份验证,操作将返回令牌。

def authenticate 
   command = AuthenticateUser.call(params[:email], params[:password]) 
   if command.success? 
      render json: { auth_token: command.result } 
   else 
      render json: { error: command.errors }, status: :unauthorized 
   end 
end

在rspec中,您有两个选项,您可以模拟此方法或创建工厂。

token based身份验证的概念是,一旦通过身份验证,用户将拥有一个令牌,并且通过提供此令牌,他将能够访问仅保留给用户的功能

请求

$ curl -H "Content-Type: application/json" -X POST -d '{"email":"example@mail.com","password":"123123123"}' http://localhost:3000/authenticate

作为回应提供令牌

{"auth_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE0NjA2NTgxODZ9.xsSwcPC22IR71OBv6bU_OGCSyfE89DvEzWfDU0iybMA"}

如果您在标头中包含令牌,请求将不会触发授权错误

$ curl -H "Authorization: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE0NjA2NTgxODZ9.xsSwcPC22IR71OBv6bU_OGCSyfE89DvEzWfDU0iybMA" http://localhost:3000/items []

因此,在执行get请求之前,请在请求标头中包含令牌

request.headers['Authorization'] = auth_token
get :your_action

如何提供auth_token的正确值?

您需要authenticate_request ApplicationController中的方法before,因为它被称为action #app/controllers/application_controller.rb class ApplicationController < ActionController::API before_action :authenticate_request attr_reader :current_user private def authenticate_request @current_user = AuthorizeApiRequest.call(request.headers).result render json: { error: 'Not Authorized' }, status: 401 unless @current_user end end

@current_user = AuthorizeApiRequest.call(request.headers).result

我相信您应该模拟这行代码,以避免收到身份验证错误。

user = FactoryBot.create(:user)
allow(AuthorizeApiRequest).to receive(:call).and_return(user)
# request.headers['Authorization'] = auth_token # this is not required anymore the authentication is skipped
get :your_action

所以我会写一些像这样的规格

request headers

我引用mock

  

通过使用before_action,每次用户发出请求时,服务器都会将AuthorizeApiRequest(使用内置对象属性request.headers)传递给result。在AuthorizeApiRequest.call(request.headers)上呼叫SimpleCommand来自attr_reader :result模块,其中@current_user被定义为ApplicationController。请求结果将返回 List<String> nonvegList = new ArrayList<String>(); nonvegList.add("Mutton Keema"); nonvegList.add("Chicken Keema"); nonvegList.add("Korma Veg Keema"); nonvegList.add("Pulaav Biryaani"); nonvegList.add("Mutton Biryaani"); nonvegList.add("Chicken Biryaani"); List<List<String>> menuList = new ArrayList<List<String>>(); menuList.add(nonvegList); ArrayList<String> resultList = new ArrayList<String>(menuList.get(0)); System.out.println(resultList); ,从而可供继承自elements = driver.find_elements_by_css_selector("#results .page_block_sub_header_count") for index in range(len(elements)): elements[index].text 的所有控制器使用。

您可以在

了解更多关于模拟的内容

pluralsight