未定义的方法`[]'为nil:NilClass在认证后使用Warden时

时间:2014-07-08 13:36:32

标签: ruby rack warden

我使用warden作为身份验证,有以下超级基本机架应用程序。

require 'rack/router'
require 'warden'
require 'ostruct'
require 'mustache'

class BadAuthenticationEndsUpHere
  def call(env)
    Rack::Response.new(
      Mustache.render('<form method="post"><input name="username" /><input type="password" name="password" /><input type="submit" />'),
      200,
      {'Content-Type' => 'text/html'}
    )
  end
end

module PowerNineStore
  class Routes
    def routes
      Rack::Builder.new do
        use Rack::Session::Cookie, :key => 'rack.session'

        use Warden::Manager do |manager|
          manager.default_strategies :password
          manager.failure_app = BadAuthenticationEndsUpHere.new
        end

        Warden::Strategies.add(:password) do
          def valid?
            params['username'] && params['password']
          end

          def authenticate!
            if params['username'] == 'foo' && params['password'] == 'bar'
              success!(OpenStruct.new(:username => 'foo'))
            else
              fail!('could not login')
            end
          end
        end

        Warden::Manager.serialize_from_session do |id|
          OpenStruct.new(:username => 'foo')
        end

        router = Rack::Router.new
        router.post('/session' => lambda { |env|
          env['warden'].authenticate!
          Rack::Response.new('authenticated!', 200, {'Location' => '/session'})
        })

        router.get('/session' => lambda { |env|
          env['warden'].authenticate!

          Rack::Response.new('authenticated!')
        })

        run router
      end
    end
  end
end

当我尝试进行身份验证时,我收到此错误:

undefined method `[]' for nil:NilClass (NoMethodError)
  /home/vagrant/.gem/ruby/2.1.1/gems/rack-1.5.2/lib/rack/utils.rb:287:in `set_cookie_header!'
  /home/vagrant/.gem/ruby/2.1.1/gems/rack-1.5.2/lib/rack/session/abstract/id.rb:362:in `set_cookie'
  /home/vagrant/.gem/ruby/2.1.1/gems/rack-1.5.2/lib/rack/session/abstract/id.rb:350:in `commit_session'
  /home/vagrant/.gem/ruby/2.1.1/gems/rack-1.5.2/lib/rack/session/abstract/id.rb:226:in `context'
  /home/vagrant/.gem/ruby/2.1.1/gems/rack-1.5.2/lib/rack/session/abstract/id.rb:220:in `call'
  /home/vagrant/.gem/ruby/2.1.1/gems/rack-1.5.2/lib/rack/builder.rb:138:in `call'

似乎headers是零,但我不确定原因。我想我根据文档正确设置了一切,但我一定错过了一些东西。有人知道这是什么吗?我在BadAuthenticationEndsUpHere课程中看到了登录页面。发布表单后,我收到此错误。

1 个答案:

答案 0 :(得分:0)

这是因为我使用Rack::Response作为机架应用程序的响应,而不是正常的机架响应数组。我已经向Warden提交了一个错误来解决它。