Rails:使用Authlogic进行基本身份验证

xpe*_*int 3 authentication ruby-on-rails authlogic

我正在使用Authlogic,我想在我的控制器中实现基本HTTP身份验证,以便我可以定义哪个操作需要身份验证.

我知道如何做基本的HTTP身份验证authenticate_or_request_with_http_basic和before_filter,但我想在其他方面如何使用Authlogic插件实现它.

class ItemsController < ApplicationController  
  before_filter :authenticate , :only => [:index, :create]
  ...
end
Run Code Online (Sandbox Code Playgroud)

arf*_*fon 28

我在以下方面取得了成功:

在application_controller.rb中定义过滤器方法

def require_http_auth_user
  authenticate_or_request_with_http_basic do |username, password|
    if user = User.find_by_login(username) 
      user.valid_password?(password)
    else
      false
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

然后在您的控制器中,您可以执行以下操作:

  before_filter : require_http_auth_user
Run Code Online (Sandbox Code Playgroud)

然后你可以使用:

http://用户名:password@yoursite.com(即http基本身份验证)

希望这可以帮助.