Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test token-based authentication?

I need some help with testing the following. I am doing the RailsCast about securing an api: http://railscasts.com/episodes/352-securing-an-api?view=asciicast

I have a RequestController with a before_filter to check if the request has a 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

My failing rspec test looks like:

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

with result: expected success? to return true, got false

I don't understand how I can inject the valid api_key in to the request so that the response will evaluate to true. Any ideas? Thanks.

like image 857
Joe Essey Avatar asked Feb 13 '23 12:02

Joe Essey


1 Answers

Token Authentication expects a HTTP_AUTHORIZATION header in this format:

Token token="my-api-token"

Also, you'll want to set the header before the get :index line:

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

You can use the encode_credentials method instead if you prefer:

request.headers["HTTP_AUTHORIZATION"] = ActionController::HttpAuthentication::Token.encode_credentials(api_key.access_token)
like image 86
Dylan Markow Avatar answered Feb 15 '23 10:02

Dylan Markow