2011-10-03 87 views

回答

10

维塔利的做法看起来像一个很好的解决方案,但一个严重的错误,授予管理员访问任何尝试登录的人,即使他们的凭据不正确。

首先,一对夫妇的功能测试(上行动需要身份验证)(它被upvoted人们不要盲目接受它的安全漏洞的“正确”答案张贴这在希望的答案)

test "admin is set with correct credentials" do 
    @request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials("user", "pass") 
    get :index 
    assert_response 200 
    assert_equal true, session[:admin] 
end 

test "admin isn't set with incorrect credentials" do 
    @request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials("user", "incorrect") 
    get :index 
    assert_response 401 
    assert_not_equal true, session[:admin] 
end 

如果使用Vitaly的代码运行此操作,则第二个测试将失败,因为session[:admin]将被设置为true,即使密码不正确。

这里是我的代码,以正确设置session[:admin],使这两个测试通过:

private 
def authenticate 
    authenticate_or_request_with_http_basic do |user_name, password| 
    session[:admin] = (user_name == "name" && password == "pass") 
    end 
end 
+0

谢谢你,你是对的。我是如何犯这个错误的。希望没有多少人受到影响。 对不起,改变正确的答案这么晚了。我没有注意到这个通知。 – Vitaly

0

您可以使用基本身份验证惨惨的工作,阅读本指南https://github.com/ryanb/cancan/wiki/changing-defaults,那么就使用康康舞为通常情况下,您可以根据登录的用户名设置权限。

+0

它看起来不错,但它增加了非必要的复杂性。我想到使用会话来检查用户是否登录的可用性。有任何想法吗? – Vitaly