I'm using HTTP Basic Authentication with Rails 3.0.9 and I need to check if the user is authorized to show 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With