Wp::Hmac
This gem wraps EY::ApiHMAC and attempts to make it easy to:
- Enable HMAC for specific routes in your Rack application.
- Add different secret keys for different customers, servers, routes or users.
It works with Rack applications like Ruby on Rails.
You should also consider using ey_api_hmac directly, especially if you only have one secret key or want HMAC enabled for every request.
Installation
Add this line to your application's Gemfile:
gem 'wp-hmac'
And then execute:
$ bundle
Or install it yourself as:
$ gem install wp-hmac
Usage
Configuration
You need to:
- Add at least one key
- Add at least one regex to match routes that will require HMAC
- Provide a mechanism to ascertain the correct key to use (via
get_auth_id_for_request
)
WP::HMAC.configure do
add_key(id: 'esso', auth_key: key['auth_key'])
add_key(id: 'texaco', auth_key: 'super_secr3t_key'])
add_hmac_enabled_route %r{^/texaco-api/}
add_hmac_enabled_route %r{^/esso-api/}
# This will be used by both the Server and Client
# in this `CurrentCustomer.name` returns either 'esso' or 'texaco'
#
# This method must be available at the Rack layer and wherever you
# use the client.
get_auth_id_for_request -> { CurrentCustomer.name }
end
You then need to slot the middleware into your rack stack. For Rails:
use WP::HMAC::Server
Using the client
Use like this ...
WP::HMAC::Client.get('https://www.example.com/api/staff')
WP::HMAC::Client.post('https://www.example.com/api/schedules, {'HEADER' => 'foo'}, 'data')
... or like this:
client = WP::HMAC::Client.new('https://www.example.com')
client.get('api/staff')
client.post('api/schedules', {}, 'data')
See Rack::Client docs for more.
Testing
You can use the client and server to test at the Rack layer without transporting over HTTP. See the spec/hmac_spec.rb
for the detail.
Contributing
- Fork it ( https://github.com/[my-github-username]/wp-hmac/fork )
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request
Thanks
Many thanks to Engine Yard for [https://github.com/engineyard/ey_api_hmac](Engine Yard HMAC api implementation).