How to enable HTTP sessions only for sub-route?

Hey,

I’m trying to add sidekiq to my webapp and want to mount the Sidekiq Web.

# frozen_string_literal: true

require "sidekiq/web"
require "sidekiq-scheduler/web"

module WebApp
  class Routes < Hanami::Routes
    mount Sidekiq::Web, at: "/sidekiq"

    slice :api, at: "/api" do
      use :body_parser, :json
      post "/graphql/api", to: "graphql.api"
    end
  end
end

Sidekiq Web needs HTTP-sessions. How to enable HTTP-sessions just for Sidekiq Web?

I cannot put following in config/app.rb, because then I get a Hanami::Action::InvalidCSRFTokenError when I request the api.

    config.actions.sessions = :cookie, {
      key: "_web_app.session",
      secret: settings.session_secret,
      expire_after: 60 * 60 * 24 * 365,
    }

Do I need to create a sidekiq slice?

thanks and best regards

:wave: Hi @wuarmin,
In the routes, you can mount Rack middleware at the level of slices and in scopes.

    scope "/sidekiq" do
      use Rack::Session::Cookie,
          key: "_my_app.session",
          secret: Hanami.app.settings.session_secret,
          expire_after: 60 * 60 * 24 * 365

      mount Sidekiq::Web, at: "/sidekiq"
    end

This code snippet is supposed to work, but it doesn’t because there is a bug in #use signature (see Ensure to mount Rack Middleware in routes using kwargs by jodosha · Pull Request #1293 · hanami/hanami · GitHub)


To disable CSRF protection, you can implement the following hook method in one action:

        private

        def verify_csrf_token?(*)
          false
        end

Of course, if you want to share this behavior across the app, implement it as a private method of your action base class (e.g., MyApp::Action in app/action.rb).

1 Like

Hey @jodosha!
Thanks for the investigation and the PR!

Has been fixed in Pass through kwargs to middleware by pat · Pull Request #1370 · hanami/hanami · GitHub