'Rails: make authentication to swagger API via devise or other

My goal is log in to Swagger API to get access to endpoints. With auth token in future.

I tryed to put Devise line in ApplicationController:

before_action :authenticate_user!

But when load http://localhost:3000/api-docs/index.html - system allows to access the API without authentication.

I tryed to uncomment in /config/initializers/rswag-ui.rb:

  c.basic_auth_enabled = true
  c.basic_auth_credentials 'username', 'password'

but it not this.

Also it did not find the right way to realize Bearer Authentication from official Swagger.io documentation. I do not know is it connected to Devise and do I need to use it.

Which way is good to log in to API via login and password of my Users? Thank you.



Solution 1:[1]

With rswag-ui you should only need to uncomment those lines. No other authentication is needed (like devise).

# /config/initializers/rswag-ui.rb

c.basic_auth_enabled = true
c.basic_auth_credentials 'username', 'password'

I just did it in my project and it worked straight away, so thought I might as well answer.

Solution 2:[2]

If you are using devise, to protect swagger enpoints you can use authorize method in config/routes.rb

  authenticate :user do
    mount Rswag::Ui::Engine => '/api-docs'
    mount Rswag::Api::Engine => '/api-docs'
  end

Mothod doc

If your API endpoints are protected with devise cookie session, only making requests after a successfully sign in will be enough. But, if your API uses other authentication scheme (Ex. Token) you will need to specify a security scheme in spec/swagger_helper.rb.

Here you can find more details for this configuration.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Julia Jacobs
Solution 2 Mateus C