5

I'm using grape, grape-swagger, and grape-swagger-rails to set up an API for my Rails 4.2.1 project. It's going to be an internal API, so I want developers to be able to access it, but not the general public. What's the best way to do that?

My initial idea was to take advantage of the api_key field that you can set in swagger-ui, but I can't figure out the right way to access it inside the root API generator for Grape.

I also thought I could try to only mount the endpoint for the documentation if the user is an admin (we're using Devise), but that doesn't hide the documentation itself (if someone knows the swagger.json link).

How have people dealt with this problem in the past?

Waynn Lue
  • 11,344
  • 8
  • 51
  • 76

2 Answers2

2

Not exactly what you asked for but it might interest some of you.

To keep swagger-ui in production, with a basic-auth:

# routes.rb
GrapeSwaggerRails::Engine.middleware.use Rack::Auth::Basic do |username, password|
  username == 'foo' && password == 'bar'
end if Rails.env.production?

mount GrapeSwaggerRails::Engine, at: "/swagger"
gtournie
  • 4,143
  • 1
  • 21
  • 22
0

You can use sorcery for authentication which adds several very handy methods (in the example below logged_in?) and in config/initializers/swagger.rb add:

GrapeSwaggerRails.options.before_filter do |request|
  unless logged_in?
    redirect_to Rails.application.routes.url_helpers.root_path
  end
end

Using api_key is also possible. In your class API < Grape::API just add before block where to check if the api_key value is correct, accessing it through params.

Brozorec
  • 1,163
  • 9
  • 15
  • I actually couldn't seem to access `api_key` in `params` inside the initializer. I don't want to have to declare it as a parameter to every API method. – Waynn Lue Oct 14 '15 at 00:04
  • I didn't mean accessing `api_key` in one of your initializers but in a `before` block in `app/api/name/api.rb`. Like that there is no need to declare it as a parameter to every API method. – Brozorec Oct 14 '15 at 06:49