Rails HTTP Basic检查是否经过身份验证?

时间:2012-06-10 22:55:17

标签: ruby-on-rails authentication http-basic-authentication

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

假设您在Rails中使用http basic auth是否有一种简单的方法来检查用户是否经过身份验证? IE浏览器。你可以在视图中做这样的事情:

- if http_basic_authenticated?
  # show admin menu

4 个答案:

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

请写下测试!

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

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

答案 2 :(得分:0)

好吧,正如我所知道的那样,没有办法说明该请求是未经过身份验证,您只能告诉该视图已通过身份验证,但为什么? 让我们看看请求的过程:

  1. 客户请求
  2. 控制器
  3. 查看
  4. 并且在第二步中,特定控制器的方法,即通过身份验证方法之前过滤,也就是说,如果您可以转到第3步 - 视图,请求必须经过身份验证

答案 3 :(得分:0)

oficial code你可以提取片段,在ApplicationController继承的任何控制器中使用这样的东西:

class ApplicationController < BaseController
  ...
  protected # Only inherited controllers can call authorized?
  def authorized?
    request.authorization.present? && (request.authorization.split(' ', 2).first == 'Basic')
  end
...
end