prevents_csrf.rb 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. module ApplicationController::PreventsCsrf
  3. extend ActiveSupport::Concern
  4. included do
  5. # disable Rails default (>= 5.2) CSRF verification because we
  6. # have an advanced use case with our JS App/SPA and the different
  7. # Auth mechanisms (e.g. Token- or BasicAuth) that can't be covered
  8. # with the built-in functionality
  9. skip_before_action :verify_authenticity_token, raise: false
  10. # register custom CSRF verification and provisioning functionality
  11. before_action :verify_csrf_token
  12. after_action :set_csrf_token_headers
  13. end
  14. private
  15. def set_csrf_token_headers
  16. return true if @_auth_type.present? && @_auth_type != 'session'
  17. # call Rails method to provide CRSF token
  18. headers['CSRF-TOKEN'] = form_authenticity_token
  19. end
  20. def verify_csrf_token
  21. return true if !protect_against_forgery?
  22. return true if request.get? || request.head?
  23. return true if %w[token_auth basic_auth].include?(@_auth_type)
  24. # call Rails method to verify CRSF token
  25. return true if valid_authenticity_token?(session, params[:authenticity_token] || request.headers['X-CSRF-Token'])
  26. logger.info 'CSRF token verification failed'
  27. raise Exceptions::NotAuthorized, 'CSRF token verification failed!'
  28. end
  29. end