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

时间:2010-02-18 00:23:26

标签: ruby-on-rails authentication authlogic

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

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

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

2 个答案:

答案 0 :(得分: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

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

  before_filter : require_http_auth_user

然后您可以使用:

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

希望这有帮助。

答案 1 :(得分:4)

Here is a great screencast逐步解释了如何在rails项目中使用authlogic。

设置authlogic后,在Application Controller中定义以下有用的与身份验证相关的帮助程序方法。

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]
相关问题