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

3

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

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

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

28

我已经成功地使用以下方法:

在application_controller.rb中定义一个filter方法。

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基本身份验证)

希望这能帮到您。


这就是我们正在寻找的内容。谢谢! - Clinton

4

这里有一个很棒的视频教程,逐步解释了如何在您的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]

我做了这个,但这不是针对REST协议的。我正在尝试创建一个基本的HTTP身份验证,其中客户端必须发送身份验证头。 - xpepermint
2
这段代码实际上并没有使用HTTP基本认证,但下面的解决方案确实使用了。 - Clinton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接