开发者

Check if the user is authorized (HTTP Basic Authentication, Rails 3.0.9)

I'm using HTTP Basic Authentication with Rails 3.0.9 and I need to check if the user is authorized to show开发者_JAVA百科 some elements in my html.erb files. How can I do that?


Vitaly's approach looks like a good solution, but has a serious bug that grants admin access to anyone who attempts to login, even if their credentials are incorrect. (Posting this as an answer in hopes that it gets upvoted and people don't blindly accept the "correct" answer with its security flaw)

First, a couple functional tests (on actions that require authentication):

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

If you run this with Vitaly's code, the second test fails because session[:admin] is being set to true, even though the password is incorrect.

Here's my code to properly set session[:admin] and make both tests pass:

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


You can make CanCan work with basic auth, read this guide https://github.com/ryanb/cancan/wiki/changing-defaults, then just use CanCan as usually, you can set permissions based on the username logged in.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜