0

我一直在谷歌上搜索这个并没有发现任何有用的东西:

假设您在 Rails 中使用 http 基本身份验证,是否有一种简单的方法可以检查用户是否经过身份验证?IE。一种您可以在视图中执行以下操作的方法:

- if http_basic_authenticated?
  # show admin menu
4

4 回答 4

3

尝试这个:

class ApplicationController < ..

  before_filter :authenticate

  def authenticate
    authenticate_or_request_with_http_basic do |username, password|
      @authenticated = username == "foo" && password == "bar"
    end
  end

  def authenticated?
    @authenticated
  end
  helper_method :authenticated?

end

您现在可以authenticated在您的视图中使用。

请写测试!

于 2012-06-11T02:36:07.443 回答
2

使用可通过ApplicationController.

class ApplicationController < BaseController

...

  def authorize
    session[:authorized] = true
  end

  def http_basic_authenticated?
    session[:authorized]
  end

  def end_session
    session[:authorized] = nil
  end

end

PS 我不是安全专家,所以我无法评论在生产环境中使用它的适用性。

于 2012-06-11T01:53:33.423 回答
0

好吧,正如我所知,没有办法告诉视图请求未通过身份验证,您可以告诉视图它已通过身份验证,但为什么呢?让我们看看请求的过程:

  1. 客户要求
  2. 控制器
  3. 看法

而在第二步中,特定控制器的方法,它是通过身份验证方法之前过滤的,也就是说,如果你可以进入第三步 - 视图,则请求必须经过身份验证

于 2012-06-11T02:17:37.550 回答
0

官方代码中,您可以提取片段以在 ApplicationController 继承的任何控制器中使用类似的内容:

class ApplicationController < BaseController
  ...
  protected # Only inherited controllers can call authorized?
  def authorized?
    request.authorization.present? && (request.authorization.split(' ', 2).first == 'Basic')
  end
...
end
于 2015-01-27T12:58:29.367 回答