ruby-on-railskeycloakomniauth

Handle csrf_detected error with omniauth and Keycloak


I am currently trying to use keycloak with a rails app using omniauth but without devise.

So here is my configuration:

Keycloak v22.0.3

omniauth-keycloak v1.5.1

omniauth v2.1.1

I followed everything from the omniauth and the keycloak-strategie documentation but I am currently facing an issue.

When I try to login my user, I received this error:

enter image description here

I tried to implement the rack_csrf from the omniauth documentation but it still does not work.

https://github.com/omniauth/omniauth#rack_csrf

my config/initializers/omniauth.rb file look like:

Rails.application.config.middleware.use OmniAuth::Builder do
  options = {
    site: 'http://localhost:8080', # L'URL de base de Keycloak
    realm: 'SecondRealm', # Le nom de votre realm Keycloak
    base_url: ''
  }

  provider :keycloak_openid, 'localApp', Rails.application.credentials.keycloak.client_secret, client_options: options,
        name: 'keycloak'
end

OmniAuth::AuthenticityTokenProtection.default_options(key: "csrf.token", authenticity_param: "_csrf")

but it still does not work

So I tried to change the session management still from the omniauth documentation:

https://github.com/omniauth/omniauth#rails-api

My config/application.rb file look like that:

require_relative "boot"

require "rails/all"

Bundler.require(*Rails.groups)

module PocRailsReactKeycloak
  class Application < Rails::Application
    config.load_defaults 7.0

    config.session_store :cookie_store, key: '_interslice_session'
    config.middleware.use ActionDispatch::Cookies # Required for all session management
    config.middleware.use ActionDispatch::Session::CookieStore, config.session_options
  end
end

But it is still not working...

So if anyone has any clue about what can I do in order to make it work?


Solution

  • I have implemented this in Rails 7 application. I have used below gems for this

    gem 'keycloak-api-rails', gem 'omniauth', gem 'omniauth-keycloak', gem 'omniauth-rails_csrf_protection'

    I think you need to add omniauth-rails_csrf_protection gem. Additionally while generating the login URL I have created state using SecureRandom.hex and stored it to session['omniauth.state'] = state and passed same state to login URL of Keycloak as well.