Rails:通过设计或其他方式进行身份验证以大摇大摆 API

Rails: make authentication to swagger API via devise or other

我的目标是登录 Swagger API 以访问端点。将来使用身份验证令牌。

我尝试在 ApplicationController 中添加 Devise 行:

before_action :authenticate_user!

但是当加载 http://localhost:3000/api-docs/index.html - 系统允许访问 API 无需身份验证。

我试图在 /config/initializers/rswag-ui.rb:

中取消注释
  c.basic_auth_enabled = true
  c.basic_auth_credentials 'username', 'password'

但不是这个。

也没有从Swagger.io官方文档中找到正确的Bearer Authentication实现方式。我不知道它是否连接到 Devise,我是否需要使用它。

通过我的用户的登录名和密码,哪种方式适合登录 API? 谢谢。

使用 rswag-ui 你应该只需要取消注释这些行。不需要其他身份验证(如设计)。

# /config/initializers/rswag-ui.rb

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

我刚刚在我的项目中做了它并且它立即起作用,所以我想我也可以回答。

如果您使用设计,为了保护 swagger enpoints,您可以使用 config/routes.rb

中的 authorize 方法
  authenticate :user do
    mount Rswag::Ui::Engine => '/api-docs'
    mount Rswag::Api::Engine => '/api-docs'
  end

Mothod doc

如果您的 API 端点受到设计 cookie 会话的保护,则仅在成功登录后发出请求就足够了。但是,如果您的 API 使用其他身份验证方案(例如令牌),您将需要在 spec/swagger_helper.rb.

中指定安全方案

Here 您可以找到此配置的更多详细信息。