goauthentik / authentik

The authentication glue you need.
https://goauthentik.io
Other
13.04k stars 867 forks source link

Redmine Integration #5986

Closed sskokorin closed 1 year ago

sskokorin commented 1 year ago

Is there a way to integrate Authentik with Redmine? Maybe there is a plugin for this? Instructions? Thank you in advance!

kidhab commented 1 year ago

It works with this plugin.

sskokorin commented 1 year ago

It works with this plugin.

Thanks a lot!

I tried to implement this, but when I try to authenticate, I get the message "Invalid SAML ticket" in the Redmine interface. Is there any manual or explanation on how to set this up with Authentik?

kidhab commented 1 year ago

There are no generic instructions because it depends on your Redmine setup.

I suggest to close this issue and open a new topic at this project's Github discussion with some more information about the things you already set up.

sskokorin commented 1 year ago

Ok! Thanks!

sskokorin commented 1 year ago

Through trial and error, I was able to set up this plugin to work with Authentik. This suits me completely.

JackPala commented 4 months ago

I have not been able to get that plugin to work with Authentik.

Does anyone have example configs? I have no idea what I'm doing wrong.

sskokorin commented 4 months ago

I have not been able to get that plugin to work with Authentik.

Does anyone have example configs? I have no idea what I'm doing wrong.

I have an installation guide for Authentik that I wrote for myself, but it is completely in Russian. If necessary, I can send it in some way.

JackPala commented 4 months ago

@sskokorin I'd be grateful, attaching it here would probably fine as long as it doesn't contain sensitive information? I can use ChatGPT and put it into English and then rewrite it into english fully when I get my instance to work, so that other people with the same issue can enjoy SSO thru Authentik on Redmine via SAML.

sskokorin commented 4 months ago

@sskokorin I'd be grateful, attaching it here would probably fine as long as it doesn't contain sensitive information? I can use ChatGPT and put it into English and then rewrite it into english fully when I get my instance to work, so that other people with the same issue can enjoy SSO thru Authentik on Redmine via SAML.

To get user attribute values, I use Python, since Russian names have a middle name. You may not use this. The guide, as it is, is presented below.

sskokorin commented 4 months ago

Redmine (версия >= 5.0.0) располагается по адресу https://redmine.example.com

Authentik располагается по адресу https://auth.example.com

Настройка на сервере Authentik

В интерфейсе Authentik переходим по пути System  -->  Certificates и нажимаем на кнопку "Generate":

В самом начале необходимо создать соответствующие сопоставления свойств.

Переходим по пути Customisation  -->  Property Mappings.

Нажимаем кнопку "Create".

Выбираем "SAML Property Mapping" и нажимаем "Next":

Нажимаем "Finish".

Нажимаем кнопку "Create".

Выбираем "SAML Property Mapping" и нажимаем "Next":

Нажимаем "Finish".

Нажимаем кнопку "Create".

Выбираем "SAML Property Mapping" и нажимаем "Next":

Нажимаем "Finish".

Нажимаем кнопку "Create".

Выбираем "SAML Property Mapping" и нажимаем "Next":

Нажимаем "Finish".

Нажимаем кнопку "Create".

Выбираем "SAML Property Mapping" и нажимаем "Next":

Нажимаем "Finish".


Переходим по пути Applications  -->  Providers и нажимаем кнопку "Create".

Выбираем "SAML Provider" и нажимаем "Next":

Все остальное оставляем по умолчанию.

Нажимаем "Create".


Переходим по пути Applications  -->  Applications и нажимаем кнопку "Create".

Нажимаем "Create".


Ограничение доступа по группе

Переходим в Applications  -->  Applications и нажимаем на название приложения, например "Redmine".

Выбираем вкладку "Policy / Group / User Bindings" и нажимаем кнопку "Bind existing policy"

Выбираем вкладку "Group" и затем выбираем в выпадающем меню группу для которой нужно предоставить доступ (для пользователей вне этой группы доступ к приложению будет закрыт)

Проверяем, что правило активировано и нажимаем "Create".


Настройка на сервере Redmine

На сервере Redmine устанавливаем плагин. Для этого выполняем шаги описанные ниже.

Устанавливаем Git на сервер (если не установлен):

apt install git

Переключаемся на пользователя redmine:

su - redmine

Переходим в директорию с установленным Redmine:

cd /opt/redmine/

Скачиваем репозитории с плагинами в соответствующие директории:

git clone https://github.com/alphanodes/additionals.git plugins/additionals

git clone https://github.com/alphanodes/redmine_saml.git plugins/redmine_saml

Копируем образец конфигурационного файла:

cp plugins/redmine_saml/contrib/sample_saml_initializers.rb config/initializers/saml.rb

Открываем скопированный файл:

nano config/initializers/saml.rb

Добавляем в него следующее содержимое:

# frozen_string_literal: true

require Rails.root.join('plugins/redmine_saml/lib/redmine_saml')
require Rails.root.join('plugins/redmine_saml/lib/redmine_saml/base')

RedmineSaml::Base.configure do |config|
  config.saml = {
    # Redmine callback URL
    assertion_consumer_service_url: "https://redmine.example.com#{RedmineSaml::CALLBACK_PATH}",
    # The issuer name / entity ID. Must be an URI as per SAML 2.0 spec.
    # sp_entity_id: 'http://redmine.example.com/auth/saml/metadata' or
    sp_entity_id: "https://redmine.example.com#{RedmineSaml::METADATA_PATH}",
    # The SLS (logout) callback URL
    single_logout_service_url: "https://redmine.example.com#{RedmineSaml::LOGOUT_SERVICE_PATH}",
    # SSO login endpoint
    idp_sso_service_url: 'https://auth.example.com/application/saml/redmine/sso/binding/redirect/',
    # SSO SSL certificate SHA-1 fingerprint
    idp_cert_fingerprint: 'insert_your_certificate_fingerprint_here',
    # Alternatively, specify the full certifiate:
    # idp_cert: "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----",
    name_identifier_format: 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent',
    # Optional signout URL, not supported by all identity providers
    signout_url: 'https://auth.example.com/if/session-end/redmine/',
    idp_slo_service_url: 'https://auth.example.com/application/saml/redmine/slo/binding/redirect/',
    # Which redmine field is used as name_identifier_value for SAML logout
    name_identifier_value: 'mail',
    # overwrite mapping seperator, if required
    # attribute_mapping_sep: '|',
    attribute_mapping: {
      # How will we map attributes from SSO to redmine attributes
      # using either urn:oid:identifier, or friendly names, e.g.
      # mail: 'extra|raw_info|urn:oid:0.9.2342.19200300.100.1.3'
      # or
      # mail: 'extra|raw_info|email'
      #
      # Edit defaults below to match your attributes
      login: 'extra|raw_info|username',
      mail: 'extra|raw_info|email',
      firstname: 'extra|raw_info|firstname',
      lastname: 'extra|raw_info|lastname',
      admin: 'extra|raw_info|admin'
    }
  }

  config.on_login do |omniauth_hash, user|
    # Implement any hook you want here
  end
end

Баг плагина!!

НЕ РАБОТАЕТ!!!!. При первой аутентификации вываливается в ошибку "Bad Request. The SAML request payload is missing."

При повторной попытке, когда пользователь аутентифицирован в Authentik, вход в Redmine удается.

Происходит только при прямом входе по адресу Redmine, когда происходит редирект на Authentik и обратно. Если переходить из интерфейса Authentik по адресу Redmine, то все проходит нормально.

На текущий момент (22/08/2023 23:54) в плагине есть баг. Если включить в настройках "Replace Redmine login page", то при попытке перейти по адресу Redmine, получим ошибку 404. Чтобы это исправить, необходимо выполнить следующие действия.

nano /opt/redmine/plugins/redmine_saml/lib/redmine_saml/patches/account_controller_patch.rb

Найти строку:

render_404

и заменить ее на:

redirect_to "https://auth.example.com/application/saml/redmine/sso/binding/init/"

Назначаем владельца и группу для директорий с плагинами:

chown -R redmine:redmine plugins/additionals/ plugins/redmine_saml/

Запускаем установку плагинов:

bundle install

bundle exec rake redmine:plugins:migrate RAILS_ENV=production

Выходим из под пользователя redmine:

exit

Перезапускаем Apache:

systemctl restart apache2


Если после выполненных действий Redmine не запустится, то проверим лог-файл ошибок Apache:

tail -f /var/log/apache2/error.log

В моем случае присутствовала ошибка вида:

App 1229 output: Error: The application encountered the following error: You have already activated base64 0.1.1, but your Gemfile requires base64 0.2.0. Since base64 is a default gem, you can either remove your dependency on it or try updating to a newer version of bundler that supports base64 as a default gem. (Gem::LoadError)
App 1229 output:     /var/lib/gems/3.1.0/gems/bundler-2.5.4/lib/bundler/runtime.rb:304:in `check_for_activated_spec!'
App 1229 output:     /var/lib/gems/3.1.0/gems/bundler-2.5.4/lib/bundler/runtime.rb:25:in `block in setup'
App 1229 output:     /var/lib/gems/3.1.0/gems/bundler-2.5.4/lib/bundler/spec_set.rb:191:in `each'
App 1229 output:     /var/lib/gems/3.1.0/gems/bundler-2.5.4/lib/bundler/spec_set.rb:191:in `each'
App 1229 output:     /var/lib/gems/3.1.0/gems/bundler-2.5.4/lib/bundler/runtime.rb:24:in `map'
App 1229 output:     /var/lib/gems/3.1.0/gems/bundler-2.5.4/lib/bundler/runtime.rb:24:in `setup'
App 1229 output:     /var/lib/gems/3.1.0/gems/bundler-2.5.4/lib/bundler.rb:162:in `setup'
App 1229 output:     /var/lib/gems/3.1.0/gems/bundler-2.5.4/lib/bundler/setup.rb:26:in `block in <top (required)>'
App 1229 output:     /var/lib/gems/3.1.0/gems/bundler-2.5.4/lib/bundler/ui/shell.rb:159:in `with_level'
App 1229 output:     /var/lib/gems/3.1.0/gems/bundler-2.5.4/lib/bundler/ui/shell.rb:111:in `silence'
App 1229 output:     /var/lib/gems/3.1.0/gems/bundler-2.5.4/lib/bundler/setup.rb:26:in `<top (required)>'
App 1229 output:     <internal:/usr/lib/ruby/vendor_ruby/rubygems/core_ext/kernel_require.rb>:85:in `require'
App 1229 output:     <internal:/usr/lib/ruby/vendor_ruby/rubygems/core_ext/kernel_require.rb>:85:in `require'
App 1229 output:     /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:380:in `activate_gem'
App 1229 output:     /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:221:in `block in run_load_path_setup_code'
App 1229 output:     /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:544:in `running_bundler'
App 1229 output:     /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:220:in `run_load_path_setup_code'
App 1229 output:     /usr/share/passenger/helper-scripts/rack-preloader.rb:91:in `preload_app'
App 1229 output:     /usr/share/passenger/helper-scripts/rack-preloader.rb:189:in `block in <module:App>'
App 1229 output:     /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:397:in `run_block_and_record_step_progress'
App 1229 output:     /usr/share/passenger/helper-scripts/rack-preloader.rb:188:in `<module:App>'
App 1229 output:     /usr/share/passenger/helper-scripts/rack-preloader.rb:30:in `<module:PhusionPassenger>'
App 1229 output:     /usr/share/passenger/helper-scripts/rack-preloader.rb:29:in `<main>'
[ E 2024-01-05 22:52:24.9596 1149/Tf age/Cor/App/Implementation.cpp:221 ]: Could not spawn process for application /opt/redmine: The application encountered the following error: You have already activated base64 0.1.1, but your Gemfile requires base64 0.2.0. Since base64 is a default gem, you can either remove your dependency on it or try updating to a newer version of bundler that supports base64 as a default gem. (Gem::LoadError)
  Error ID: 22b8c53f
  Error details saved to: /tmp/passenger-error-cq5N2g.html

[ E 2024-01-05 22:52:24.9639 1149/T9 age/Cor/Con/CheckoutSession.cpp:281 ]: [Client 1-1] Cannot checkout session because a spawning error occurred. The identifier of the error is 22b8c53f. Please see earlier logs for details about the error.

Это означает, что в Gemfile указана более новая версия, чем та, которая установлена на сервере.

Переходим в директорию с установленным Redmine:

cd /opt/redmine/

Чтобы обновить пакет до указанной в файле, нужно выполнить команду:

gem install base64

Перезапустим Apache:

systemctl restart apache2


В веб-интерфейсе Redmine переходим по пути Администрирование  -->  Модули  -->  Redmine SAML  -->  Параметры.

На вкладке "Настройки" выполняем следующие настройки:

Готово. Настройка окончена.