【问题标题】:Rails: Basic Authentication with AuthlogicRails:使用 Authlogic 进行基本身份验证
【发布时间】:2010-02-18 00:23:26
【问题描述】:

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

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

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

【问题讨论】:

    标签: ruby-on-rails authentication authlogic


    【解决方案1】:

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

    在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基本认证)

    希望这会有所帮助。

    【讨论】:

    • 这就是我们想要的。谢谢!
    • 你拯救了我的一天!谢谢!
    【解决方案2】:

    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]
    

    【讨论】:

    • 我这样做了,但这不适用于 REST 协议。我正在尝试创建一个基本 HTTP 身份验证,其中客户端必须发送身份验证标头。
    • 这段代码实际上并没有使用 HTTP Basic,但下面的解决方案可以。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    • 2017-06-13
    • 2013-05-30
    • 2011-05-07
    • 2016-05-31
    • 2017-10-06
    相关资源
    最近更新 更多