The Merb Open Source Book has a chapter on authentication. However, the testing an authenticated request section example only shows what you can do for forms based authentication. I have a web service that I want to test with HTTP basic authentication. How would I do that?
After posting my question, I tried a few more things and found my own answer. You can do something like the following:
response = request('/widgets/2222',
:method => "GET",
"X_HTTP_AUTHORIZATION" => 'Basic ' + ["myusername:mypassword"].pack('m').delete("\r\n"))
I may get around to updating the book, but at least this info is here for Google to find and possibly help someone else.
Here is an example for HTTP basic auth from inside a controller:
class MyMerbApp < Application
before :authenticate, :only=>[:admin]
def index
render
end
def admin
render
end
protected
def authenticate
basic_authentication("Protected Area") do |username, password|
username == "name" && password == "secret"
end
end
end
you'll need to define the merb_auth_slice in config/router.rb if it's not already done for you:
Merb::Router.prepare do
slice(:merb_auth_slice_password, :name_prefix => nil, :path_prefix => "")
end
Related
I need collect all "title" from all pages from site.
Site have HTTP Basic Auth configuration.
Without auth I do next:
require 'anemone'
Anemone.crawl("http://example.com/") do |anemone|
anemone.on_every_page do |page|
puts page.doc.at('title').inner_html rescue nil
end
end
But I have some problem with HTTP Basic Auth...
How I can collected titles from site with HTTP Basic Auth?
If I try use "Anemone.crawl("http://username:password#example.com/")" then I have only first page title, but other links have http://example.com/ style and I received 401 error.
HTTP Basic Auth works via HTTP headers. Client, willing to access restricted resource, must provide authentication header, like this one:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
It contains name and password, Base64-encoded. More info is in Wikipedia article: Basic Access Authentication.
I googled a little bit and didn't find a way to make Anemone accept custom request headers. Maybe you'll have more luck.
But I found another crawler that claims it can do it: Messie. Maybe you should give it a try
Update
Here's the place where Anemone sets its request headers: Anemone::HTTP. Indeed, there's no customization there. You can monkeypatch it. Something like this should work (put this somewhere in your app):
module Anemone
class HTTP
def get_response(url, referer = nil)
full_path = url.query.nil? ? url.path : "#{url.path}?#{url.query}"
opts = {}
opts['User-Agent'] = user_agent if user_agent
opts['Referer'] = referer.to_s if referer
opts['Cookie'] = #cookie_store.to_s unless #cookie_store.empty? || (!accept_cookies? && #opts[:cookies].nil?)
retries = 0
begin
start = Time.now()
# format request
req = Net::HTTP::Get.new(full_path, opts)
response = connection(url).request(req)
finish = Time.now()
# HTTP Basic authentication
req.basic_auth 'your username', 'your password' # <<== tweak here
response_time = ((finish - start) * 1000).round
#cookie_store.merge!(response['Set-Cookie']) if accept_cookies?
return response, response_time
rescue Timeout::Error, Net::HTTPBadResponse, EOFError => e
puts e.inspect if verbose?
refresh_connection(url)
retries += 1
retry unless retries > 3
end
end
end
end
Obviously, you should provide your own values for the username and password params to the basic_auth method call. It's quick and dirty and hardcode, yes. But sometimes you don't have time to do things in a proper manner. :)
I've stumbled across a bit of problem when it comes to redirects behind a protected set of URLs (admin section) within a Sinatra app. It most likely a silly mistake but I haven't found anything online that helps.
This is for a password protected area as the helpers show, where the user can create new events. The first time a user tries to access the admin, they are prompted for a password, then subsequent pages are left. The problem I have is that when the app attempts to redirect after a successful new event is made, the user has to re-auth themselves ... which seems bit redundant.
This also applies for the deletion and editing process, the user always gets prompted when a redirect is attempted. I've tried passing 303 at the second parameter to for a different HTTP code, but to no avail
Anyway, here's the code, any questions/help would be appreciated
helpers do
def protected!
unless authorized?
response['WWW-Authenticate'] = %(Basic realm="Restricted Area")
throw(:halt, [401, "Not authorized\n"])
end
end
def authorized?
#auth ||= Rack::Auth::Basic::Request.new(request.env)
#auth.provided? && #auth.basic? && #auth.credentials && #auth.credentials == ['admin', 'admin']
end
end
...
get "/admin/events/:id" do
protected!
conf = Conference.where(:_id => params[:id]).first
not_found unless conf
haml :admin_event_edit, :layout => :admin_layout, :locals => { :event => conf }
end
post "/admin/events/new/" do
protected!
conf = Conference.new(params[:event])
if conf.save!
redirect "/admin/events/"
else
"Something went horribly wrong creating the new event, heres the form contents #{params.inspect}"
end
end
get "/admin/events/" do
protected!
haml :admin_events, :layout => :admin_layout, :locals => { :our_events => Conference.where(:made => true).order_by(:start_date.asc).limit(15), :other_events => Conference.where(:made => false).order_by(:start_date.asc).limit(15)}
end
Is this only happening in Safari?
I've used the code above and it only re-auths in Safari, Chrome, and FireFox work as expected.
It seems that if you unless you check the "remember my username/password" Safari will send each subsequent request without the Authorization in the header (a great tool for watching headers etc is Charles). If you do check it then Apple sends the Auth in the header correctly and even if you quit out of Safari it will continue to remember to send the Auth on relaunch.
So it's Apple being silly not you :)
I am trying to use OmniAuth to handle the OAuth flow for a small-ish Sinatra app. I can get 37signals Oauth to work perfectly, however I'm trying to create a strategy for Freshbooks Oauth as well.
Unfortunately Freshbooks require OAuth requests to go to a user specific subdomain. I'm acquiring the subdomain as an input and I then need to persistently use the customer specific site URL for all requests.
Here's what I've tried up to now. The problem is that the new site value doesn't persist past the first request.
There's to to be a simple way to achieve this but I'm stumped.
#Here's the setup -
def initialize(app, consumer_key, consumer_secret, subdomain='api')
super(app, :freshbooks, consumer_key, consumer_secret,
:site => "https://"+subdomain+".freshbooks.com",
:signature_method => 'PLAINTEXT',
:request_token_path => "/oauth/oauth_request.php",
:access_token_path => "/oauth/oauth_access.php",
:authorize_path => "/oauth/oauth_authorize.php"
)
end
def request_phase
#Here's the overwrite -
consumer.options[:site] = "https://"+request.env["rack.request.form_hash"]["subdomain"]+".freshbooks.com"
request_token = consumer.get_request_token(:oauth_callback => callback_url)
(session[:oauth]||={})[name.to_sym] = {:callback_confirmed => request_token.callback_confirmed?,
:request_token => request_token.token,
:request_secret => request_token.secret}
r = Rack::Response.new
r.redirect request_token.authorize_url
r.finish
end
Ok, here's a summary of what I did for anyone who comes across this via Google.
I didn't solve the problem in the way I asked it, instead I pushed the subdomain into the session and then I overwrite it whenever the site value needs to be used.
Here's the code:
#Monkeypatching to inject user subdomain
def request_phase
#Subdomain is expected to be submitted as <input name="subdomain">
session[:subdomain] = request.env["rack.request.form_hash"]["subdomain"]
consumer.options[:site] = "https://"+session[:subdomain]+".freshbooks.com"
super
end
#Monkeypatching to inject subdomain again
def callback_phase
consumer.options[:site] = "https://"+session[:subdomain]+".freshbooks.com"
super
end
Note that you still have to set something as the site when it's initialised, otherwise you will get errors due to OAuth not using SSL to make the requests.
If you want to see the actual code I'm using it's at: https://github.com/joeharris76/omniauth I'll push the fork up to the main project once I've battle tested this solution a bit more.
Is it possible to use OAuth with HTTParty? I'm trying to do this API call, but, contradictory to the documentation, it needs authentication.
Before you say "Use a Twitter-specific Gem", hear me out--I've tried. I've tried twitter, grackle, and countless others, but none support this specific API call. So, I've turned to HTTParty.
So, how could I use OAuth with HTTParty?
I've been using the vanilla OAuth gem to implement a few simple Twitter API calls. I didn't need a heavyweight gem to do everything, and I was already using OAuth, so a 'roll-your-own' approach seemed reasonable. I know that I haven't mentioned HTTParty, so please don't ding me for that. This may be useful to others for the essence of easy Twitter OAuth if you're already using the OAuth gem.
In case it is helpful, here is the pertinent code (sorry about mixing some constants and other variables / methods at the start - it was the easiest and most accurate way to extract this from my real code):
#Set up the constants, etc required for Twitter OAuth
OAUTH_SITE = "https://api.twitter.com"
TOKEN_REQUEST_METHOD = :post
AUTHORIZATION_SCHEME = :header
def app_request_token_path
"/oauth/request_token"
end
def app_authorize_path
"/oauth/authorize"
end
def app_access_token_path
"/oauth/access_token"
end
def consumer_key
"your twitter API key"
end
def consumer_secret
"your twitter API secret"
end
# Define the OAuth consumer
def consumer meth=:post
#consumer ||= OAuth::Consumer.new(consumer_key,consumer_secret, {
:site => "#{OAUTH_SITE}",
:request_token_path=>app_request_token_path,
:authorize_path=>app_authorize_path,
:access_token_path=>app_access_token_path,
:http_method=>:post,
:scheme=> :header,
:body_hash => ''
})
end
# Essential parts of a generic OAuth request method
def make_request url, method=:get, headers={}, content=''
if method==:get
res = #access_token.get(url, headers)
elsif method==:post
res = #access_token.post(url, content, headers)
end
if res.code.to_s=='200'
jres = ActiveSupport::JSON.decode(res.body)
if jres.nil?
#last_status_text = #prev_error = "Unexpected error making an OAuth API call - response body is #{res.body}"
end
return jres
else
#last_status_text = #prev_error = res if res.code.to_s!='200'
return nil
end
end
# Demonstrate the daily trends API call
# Note the use of memcache to ensure we don't break the rate-limiter
def daily_trends
url = "http://api.twitter.com/1/trends/daily.json"
#last_status_code = -1
#last_status_success = false
res = Rails.cache.fetch(url, :expires_in=> 5.minutes) do
res = make_request(url, :get)
unless res
#last_status_code = #prev_error.code.to_i
end
res
end
if res
#last_status_code = 200
#last_status_success = true
#last_status_text = ""
end
return res
end
I hope this, largely in context of broader use of the OAuth gem, might be useful to others.
I don't think that HTTParty supports OAuth (though I am no expert on HTTParty, it's way too high-level and slow for my taste).
I would just call the Twitter request directly using OAuth gem. Twitter API documentation even has an example of usage: https://dev.twitter.com/docs/auth/oauth/single-user-with-examples#ruby
I used a mix of the OAuth2 gem to get the authentication token and HTTParty to make the query
client = OAuth2::Client.new(apiKey, apiSecret,
:site => "https://SiteForAuthentication.com")
oauthResponse = client.password.get_token(username, password)
token = oauthResponse.token
queryAnswer = HTTParty.get('https://api.website.com/query/location',
:query => {"token" => token})
Not perfect by a long way but it seems to have done the trick so far
I'm trying to use Shoes' download() method to pass a username and password in the HTTP header to authenticate the HTTP request (talking to a Rails app).
I'm a bit of a newb when it comes to this stuff.
I havn't quite understood whether I should be automatically able to use the below syntax (username:pwd#) or whether the username and password should be created manually inside the HTTP header (which I think I can also access using :headers of the download method).
download "http://username:pwd#127.0.0.1:3000/authenticate", :method => "POST" do |result|
# process result.response.body here
end
Any help would be appreciated
Can I answer my own question?
This seems to do the trick:
require 'base64'
< ... snip ... >
# create the headers
headers = {}
headers['Authorization'] = 'Basic ' + encode64("#{#login.text()}:#{#pword.text()}").chop
# run the download
download "#{$SITE_URL}/do_something", :method => "GET", :headers => headers do |result|
#status.text = "The result is #{result.response.body}"
end