【问题标题】:Configuring Warden with Grape API application使用 Grape API 应用程序配置 Warden
【发布时间】:2014-10-24 13:49:50
【问题描述】:

我已经在 config/initializers/warden.rb 的 Rails/Grape API 应用程序中配置了 Warden:

Rails.application.config.middleware.use Warden::Manager do |manager|
  manager.default_strategies :password
end

(我会分享password 策略代码,但它确实不适用于这个问题。我将它存储在config/initializers/warden/strategies/password.rb。)

当我使用无效的登录凭据运行 RSpec 请求规范时:

describe 'session_tokens', type: :request do
  let!(:user)      { FactoryGirl.create(:user) }
  let(:ip_address) { Faker::Internet.ip_v4_address }

  describe 'POST /' do
    context 'with invalid password' do
      before do
        post '/api/v1/session_tokens', email: user.email, password: "#{user.password}.", ip: ip_address
      end

      it 'is unsuccessful' do
        expect(response.code).to eql '401'
      end

      it 'has an "X-Error-Detail" header' do
        expect(response.header['X-Error-Detail']).to eql 'Invalid email or password.'
      end
    end
  end
end

它给了我这个错误:

Failure/Error: post '/api/v1/session_tokens', email: user.email, password: "#{user.password}.", ip: ip_address
RuntimeError:
   No Failure App provided

在我的一生中,在查看在线示例后,我无法让 Warden 正确使用 Grape(例如,dblock/grape_warden)。大多数示例都很简单,将 Grape 应用本身设置为失败应用。

当我在 Grape 应用程序中将一个模块作为 failure_app 传递时:

Rails.application.config.middleware.use Warden::Manager do |manager|
  manager.default_strategies :password
  manager.failure_app = -> (env) { API::V1::SessionTokens }
end

我收到此错误,即使我在该模块中有 post :unauthenticated 块:

Failure/Error: post '/api/v1/session_tokens', email: user.email, password: "#{user.password}.", ip: ip_address
NoMethodError:
  undefined method `unauthenticated' for API::V1::SessionTokens:Class

当我将 unauthenticated 定义移动到我的 Grape 应用程序的根目录时,也会发生同样的情况。

【问题讨论】:

    标签: ruby-on-rails warden grape-api


    【解决方案1】:

    解决方案是在 Grape 应用程序本身而不是在 Rails 初始化程序中配置 Warden。

    我删除了 config/initializers/warden.rb 并将其内容放入我的 Grape 应用程序中:

    module API
      module V1
        class Base < Grape::API
          mount API::V1::SessionTokens
    
          use Warden::Manager do |manager|
            manager.default_strategies :password
            manager.failure_app = API::V1::SessionTokens
          end
        end
      end
    end
    

    现在完美运行!

    特别感谢 Jean Bahnik this file on GitHub。几乎放弃后才发现这段漂亮的代码。

    【讨论】:

      猜你喜欢
      • 2013-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-22
      • 2011-08-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多