Sidekiq一直喊着CSRF保护,路由却挂载在里面Rails.application.routes.draw

Sidekiq keeps yelling at CSRF protection, but the route is mounted inside Rails.application.routes.draw

我有 Rails 6.0.3.5 API,我没有使用 Devise 进行身份验证。 当我尝试访问 sidekiq UI 时,它大喊:

Sidekiq::Web needs a valid Rack session for CSRF protection. If this is a Rails app, make sure you mount Sidekiq::Web *inside* your application routes: Rails.application.routes.draw do mount Sidekiq::Web => "/sidekiq" .... end

但实际上我的路线是这样的:

Rails.application.routes.draw do
  mount Sidekiq::Web => '/sidekiq'

  namespace :api do
    namespace :v1 do
     ...
    end
  end
end

我在 config/initializers/sidekiq.rb 中用 user/pass 保护了路由,就像这样:

require 'sidekiq'
require 'sidekiq/web'
Sidekiq::Web.use(Rack::Auth::Basic) do |user, password|  
  Rack::Utils.secure_compare(::Digest::SHA256.hexdigest(user), ::Digest::SHA256.hexdigest(ENV["SIDEKIQ_USER"])) &
    Rack::Utils.secure_compare(::Digest::SHA256.hexdigest(password), ::Digest::SHA256.hexdigest(ENV["SIDEKIQ_PASSWORD"]))
end

有什么想法吗?

这似乎是一个与 v 6.2.0 有关的问题,如 Sidekiq's Github 中所述。

我已经降级到 v 6.1.3 并且成功了。

您正在 API 模式下使用 Rails,它不提供会话,因此您无法安装依赖于会话的其他 Rack 应用程序。记录于此:

https://edgeguides.rubyonrails.org/api_app.html#using-session-middlewares

Github 用户“gagalago”在此处给出的解决方案。它对我有用!

在您的 config/routes.rb 文件中添加:

require 'sidekiq/web'

# Configure Sidekiq-specific session middleware
Sidekiq::Web.use ActionDispatch::Cookies
Sidekiq::Web.use ActionDispatch::Session::CookieStore, key: "_interslice_session"

Myapp::Application.routes.draw do
  mount Sidekiq::Web => "/sidekiq"
  # ...
end

https://github.com/mperham/sidekiq/issues/4850#issuecomment-810880012