2010-02-18 62 views
3

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

我知道如何做基本的HTTP身份验证authenticate_or_request_with_http_basic一个before_filter,但我想在这里从其他如何实现它与Authlogic插件。

class ItemsController < ApplicationController 
    before_filter :authenticate , :only => [:index, :create] 
    ... 
end 

回答

4

Here is a great screencast解释,一步一步,如何在Rails项目中使用authlogic。

一旦设置了authlogic,请在您的应用程序控制器中定义以下有用的身份验证相关帮助程序方法。

def current_user_session 
    return @current_user_session if defined?(@current_user_session) 
    @current_user_session = UserSession.find 
end 

def current_user 
    return @current_user if defined?(@current_user) 
    @current_user = current_user_session && current_user_session.record 
end 

def require_user 
    unless current_user 
    store_location 
    flash[:notice] = "You must be logged in to access this page" 
    redirect_to new_user_session_url 
    return false 
    end 
end 

def require_no_user 
    if current_user 
    store_location 
    flash[:notice] = "You must be logged out to access this page" 
    redirect_to root_url 
    return false 
    end 
end 

一旦这些方法被定义,你可以指定需要用户采取行动的记录:

before_filter :require_user, :only => [:new, :edit] 
+0

我这样做了,但这不适用于REST协议。我试图创建一个基本的HTTP身份验证,客户端必须发送身份验证头。 – xpepermint 2010-02-18 08:39:40

+0

ow ....因为我发现插件默认处理授权。哼... – xpepermint 2010-02-18 08:51:49

+2

这段代码实际上并不使用HTTP Basic,但下面的解决方案确实如此。 – Judy 2010-03-10 19:56:11

28

我已经受够了以下成功:

定义的过滤方法in 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 

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

before_filter : require_http_auth_user 

然后,您可以使用:

http://username:[email protected](即http基本认证)

希望这会有所帮助。

+0

这就是我们正在寻找的。谢谢! – Judy 2010-03-10 19:56:27

+0

你已经救了我的一天!谢谢! – sgonzalez 2012-06-04 12:41:25

相关问题