Wednesday, October 2, 2013

Rails 4, Cucumber, Capybara and HTTP Token Authorization

I just watched Ryan Bates excellent Railscast on securing an API with a simple api access_token.  That was pretty awesome until I went to implement it and 12 hours later I'm still struggling to figure out how this
  authenticate_or_request_with_http_token do |token, options|  
   ApiKey.exists?(access_token: token)  
  end  
works with Cucumber.  There is an awesome gem for helping developers test API's with Cucumber called cucumber-api-steps and it has step definitions for doing HTTP Basic Authorization [link] but does not provide any methods for doing Token based Authorization.  This started me down the path of trying to figure out the
 authenticate_or_request_with_http_token  
method.  Unless the Token string is formatted correctly, this method will always fail and return a
 ["HTTP Token: Access denied."]  
So before you spend half a day like I did fumbling around with Rack, Cucumber:
 page.driver.header('Authorization', 'Token token=token_value, option_1=ghi, option_2=qwer')  
You can drop that line anywhere in your Cucumber steps and it will set the appropriate headers.  I hope this helps someone out there!

1 comment:

  1. Fuck, I've been waiting my entire life for that gem of information. Thanks bro.

    ReplyDelete