HmacSignature

Credit to Martyn Loughran and the 'signature' gem, which HmacSignature is based on.

Examples

Client example (Sending auth via query_string/post body)

params       = {:some => 'parameters'}
token        = HmacSignature::Token.new('my_key', 'my_secret')
request      = HmacSignature::Strategy::Params::Request.new('POST', '/api/thing', params)
auth_hash    = request.sign(token)
query_params = params.merge(auth_hash)

HTTParty.post('http://myservice/api/thing', {
  :query => query_params
})

query_params looks like:

{
  :some           => "parameters",
  :auth_timestamp => 1273231888,
  :auth_signature => "28b6bb0f242f71064916fad6ae463fe91f5adc302222dfc02c348ae1941eaf80",
  :auth_version   => "1.0",
  :auth_key       => "my_key"
}

Client example (Sending auth via headers)

params       = {:some => 'parameters'}
token        = HmacSignature::Token.new('my_key', 'my_secret')
request      = HmacSignature::Strategy::Headers::Request.new('POST', '/api/thing', params)
auth_headers = request.sign(token)

HTTParty.post('http://myservice/api/thing', {
  :query => params, 
  :headers => auth_headers
})

auth_headers looks like:

{
  'X-Auth-Expires'   => 1273231888,
  'X-Auth-Signature' => "28b6bb0f242f71064916fad6ae463fe91f5adc302222dfc02c348ae1941eaf80",
  'X-Auth-Version'   => "1.0",
  'X-Auth-Key'       => "my_key"
}

Server example (sinatra)

error HmacSignature::AuthenticationError do |controller|
  error = controller.env["sinatra.error"]
  halt 401, "401 UNAUTHORIZED: #{error.message}\n"
end

post '/api/thing' do
  request = HmacSignature::Strategy::Params::Request.new('POST', env["REQUEST_PATH"], params)
  # This will raise a HmacSignature::AuthenticationError if request does not authenticate
  token = request.authenticate do |key|
    HmacSignature::Token.new(key, lookup_secret(key))
  end

  # Do whatever you need to do
end

Developing

bundle
bundle exec rspec spec/*_spec.rb

Please see the travis status for a list of rubies tested against

Copyright (c) 2013 Erik Lott. See LICENSE for details.