14

I have a Rails 6.0.3.5 API, and i'm NOT using Devise for authentication. When I try to access sidekiq UI, it yells:

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

But actually my routes are exactly like that:

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

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

I've protected the route with user/pass in config/initializers/sidekiq.rb like that:

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

Any ideas?

João Ramires
  • 723
  • 10
  • 23

4 Answers4

31

Solution given by Github user "gagalago" here. It worked for me!

Have this in your config/routes.rb file:

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

Aleksandrus
  • 1,589
  • 2
  • 19
  • 31
  • 2
    Works perfectly, thank you. This should be the suggested answer to add Sidekiq Web support to Rails api-only applications when updating to the latest sidekiq version. – saquino88 May 06 '21 at 12:42
  • Also a solution: Sidekiq::Web.use Rack::Session::Cookie, secret: 'SecretKey' – Conor Sep 21 '22 at 09:33
7

You are using Rails in API mode, where it does not provide a session so you can't mount other Rack apps which depend on a session. Documented here:

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

Mike Perham
  • 21,300
  • 6
  • 59
  • 61
0

For bare Rack apps:

use Rack::Session::Cookie, secret: "your_SECURE_key", same_site: true, max_age: 86400
run Sidekiq::Web

More info: https://github.com/mperham/sidekiq/blob/main/Changes.md#620

Rodion V
  • 321
  • 3
  • 10
-3

This seems to be an issue related to v 6.2.0 as described in Sidekiq's Github.

I've downgraded to v 6.1.3 and it worked.

João Ramires
  • 723
  • 10
  • 23