ditojanelidze
ditojanelidze

Reputation: 90

JWT validation in rails requests

I have authentication service using

Json Web Token

in my Rails API. I want to check if Token is valid in every request my API gets.

Problem is that when i write function which checks if Token is valid in main

application_controller.rb

file it is not visible in engines and i can't do before_action for every engine i have. is there any way to validate Token in every request my application gets in every engine?

Upvotes: 2

Views: 1064

Answers (1)

gaotongfei
gaotongfei

Reputation: 353

You can create a .rb file under config/initializers

class ActionController::Base
  before_action :validate_jwt_token

  def validate_jwt_token
    # validate jwt token
  end
end

This will make sure validate_jwt_token is executed on every request among all of the mounted engines.

Edit:

You can also put this code under Api engine or Umg's engine.rb

module Api
  class Engine < ::Rails::Engine
    #...

    initializer 'api.jwt_token_validation_helper' do
      ActionController::Base.send :include, Api::JwtTokenValidationHelper
    end
  end
end

module Api
  module JwtTokenValidationHelper
    extend ActiveSupport::Concern

    include do
      before_action :validate_jwt_token

      def validate_jwt_token
        puts 'your code here'
      end
    end
  end
end

Upvotes: 1

Related Questions