我使用的是Rails 5 API模式
routs.rb:
Rails.application.routes.draw do
constraints Basic do
mount Rswag::Ui::Engine => '/api-docs'
mount Rswag::Api::Engine => '/api-docs'
mount Sidekiq::Web => '/sidekiq'
# etc
end
end
constraints / basic.rb:
class Basic
def self.matches?(request)
authenticate_or_request_with_http_basic do |email, password|
email == 'foo' && password = 'bar'
end
end
end
但是我收到了一个错误:
NoMethodError(基本:类的未定义方法`authenticate_or_request_with_http_basic')
我可以在约束中使用http basic auth吗?
答案 0 :(得分:1)
我认为你不能在控制器范围之外使用authenticate_or_request_with_http_basic
方法。您可以使用auth check in general controller设置before_filter
。以下是docs comments:
class AdminController < ApplicationController
before_filter :authenticate
def authenticate
authenticate_or_request_with_http_basic('Administration') do |email, password|
email == 'foo' && password == 'bar'
end
end
end
这也是我发现的Rails Authentication Routing Constraints Considered Harmful。
话虽如此,我认为有一种方法:
class Basic
def self.matches?(request)
if ActionController::HttpAuthentication::Basic.has_basic_credentials?(request)
credentials = ActionController::HttpAuthentication::Basic.decode_credentials(request)
email, password = credentials.split(':')
email == 'foo' && password == 'bar'
end
end
end