Ruby on rails - rack middleware exclude - is it possible?

有些话、适合烂在心里 提交于 2019-12-20 02:53:19

问题


I am trying a rack middleware, to do authentication in a separate layer. The problem is, all request goes through this layer. I don't want the asset request like css, javascript to go through authentication middleware., I also don't want logout flow to go through this.,

In application.rb

config.middleware.use AuthClient::MyFilterClass

I am expecting something like

config.middleware.use AuthClient::MyFilterClass, :exclude => [:logout,'*/assets/*']

Is there any way to exclude custom path / actions from middleware ?


回答1:


Rack middlewares form a up and down stack, like the following example:

This means that whatever the request your making, it will pass through all middlewares no matter what.
So you can't exclude middlewares like this.

What you can do though, is inject your own middleware to the stack, which will check the request path and call some other middlewares or not.

Something like this:

class MyMiddleware
  def initialize(app)
    @app = app
  end

  def call(env)
    if env['REQUEST_PATH'].match(/^\/assets\//)
      middleware = AuthClient::MyFilterClass.new(@app)
      env = middleware.call(env)
    end

    @app.call(env)
  end
end

This will call the AuthClient::MyFilterClass middleware conditionnally depending of the request path.




回答2:


These are my findings, while working on this issue :

  1. Rack middleware doesn't have any feasibility to handle an exclude pattern / exclude action injection.,

I agree with Damien MATHIEU., In extreme case, we could achieve by filtering based on request object., Here is my code example :

def call(env)
  if (should_authenticate(env))
    //do auth related stuff
  end

  @app.call(env)
end

private
  def should_authenticate(env)
    request = Request.new(env)
    return false if request.content_length.zero?
   strategy = other_conditions(env)
   return false unless strategy

case strategy
when 'condition1'
  //conditional logic
when 'condition2'
  //conditional logic
else
  false
end
end

def other_conditions(env)
 if env['REQUEST_PATH'].match(/^\/assets\//)
   return 'condition1'
 end
//Check for other pre-validations to do
end


来源:https://stackoverflow.com/questions/22198859/ruby-on-rails-rack-middleware-exclude-is-it-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!