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

I am using HTTP Basic Authentication with Rails 3.0.9, and I need to check if the user is allowed to show some elements in my html.erb files. How can i do this?

+6
source share
2 answers

Vitaly's approach looks like a good solution, but it has a serious error that gives the administrator access to everyone who is trying to log in, even if their credentials are incorrect. (Conducting this as an answer in the hope that he will receive support, and people do not blindly accept the โ€œrightโ€ answer with its lack of security)

First, a couple of functional tests (for 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 will fail because session[:admin] set to true, even if the password is incorrect.

Here is my code to set session[:admin] correctly and run both tests:

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

You can get CanCan to work with basic auth, read this guide https://github.com/ryanb/cancan/wiki/changing-defaults , and then just use CanCan, as usual, you can set permissions based on username.

0
source

Source: https://habr.com/ru/post/898530/


All Articles