Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 563
João Ramires Avatar asked Mar 22 '21 20:03

João Ramires


2 Answers

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

like image 112
Aleksandrus Avatar answered Nov 05 '22 07:11

Aleksandrus


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

like image 44
Mike Perham Avatar answered Nov 05 '22 08:11

Mike Perham