GrapeDeviseTokenAuth gem is a compatibility layer between devise_token_auth
and grape. It is useful when mounting a grape API in a rails application
where devise (or
devise) is already present. It is
devise, therefore it is not suitable for
grape where these are not present. If you are looking for a pure grape solution,
you should check out grape_token_auth.
The majority of the hard work and credit goes to Lyann Dylan Hurley and his fantastic devise_token_auth gem. I merely have ported this to work well with grape.
Add this line to your application's Gemfile:
And then execute:
Or install it yourself as:
$ gem install grape_devise_token_auth
Place this line in an initializer in your rails app or at least somewhere before the grape API will get loaded:
Within the Grape API:
class Posts < Grape::API auth :grape_devise_token_auth, resource_class: :user helpers GrapeDeviseTokenAuth::AuthHelpers # ... end
The resource class option allows you to specific the scope that will be authenticated, this corresponds to your devise mapping.
Individual endpoints can now be authenticated by calling
get '/' do authenticate_user! present Post.all end
alternatively to protect all routes place the call in a before block:
before do authenticate_user! end
There is also a
authenticate_user version of this helper (notice that it lacks of exclamation mark) that doen't fail nor returns 401.
A full example setup can be found here
Note about ignoring existing warden users
If you are having issues with users persisting across logins or you do not want to integrate with devise, you can disable the integration with devise during setup as so:
GrapeDeviseTokenAuth.setup! do |config| config.ignore_existing_warden_users = true end
Testing and Example
Currently I am using this repo to test this gem, eventually I plan on
migrating the tests into the
grape_devise_token_auth repo. For now though, I
refer you to that repo for how to integrate with an existing
After checking out the repo, run
bin/setup to install dependencies. Then, run
bin/console for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run
bundle exec rake install. To release a new version, update the version number in
version.rb, and then run
bundle exec rake release to create a git tag for the version, push git commits and tags, and push the
.gem file to rubygems.org.
- Fork it ( https://github.com/[my-github-username]/grape_devise_token_auth/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