In Restful Authentication, lib/authenticated_system.rb
,
why does current_user
do a login_from_basic_auth
, which does a authenticate_with_http_basic
, which is to check the HTTP user provided login name and password?
I thought the login form is in /session/new
(or /login
), and then it POST to /session
, which will go to the sessions
controller, create
action, and there, it
verifies the login name and password provided by the user.
This is line 8 of lib/authenticated_system.rb
def current_<%= file_name %>
@current_user ||= (login开发者_开发技巧_from_session
|| login_from_basic_auth
|| login_from_cookie) unless @current_user == false
end
So the question is, if the login name and password was previously verified, then why checking it in current_user
?
This function indicates that there are three ways to authenticate in your system:
- Using a POST request from /session/new or /login.
- Using BASIC HTTP authentication (a popup or URL provided username and password).
- Using a remember me cookie so that sessions can persist even when session cookies are destroyed or the browser is restarted.
Even though your basic login happens with a POST request from /session/new or /login, the only thing that POST request actually does is set the session user id (probably session[:user_id]). Once that session[:user_id] has been set, you no longer need to login to perform a request, because you are authenticated. From this point forward the actual authentication happens by checking the session[:user_id] to see if someone has already logged in.
Here is a more detailed authentication lifecycle (for login):
- User visits /login.
- User enters password and username and submits form.
- Password is checked, if authenticated the session[:user_id] is set.
- User visits another page.
- To check if the user is authenticated, current_user is called.
- login_from_session is called and the user corresponding to session[:user_id] is returned.
- The user is considered authenticated.
Here is a more detailed authentication lifecycle (for HTTP BASIC authentication):
- A user visits http://username:password@www.example.com.
- To check if the user is authenticated, current_user is called.
- login_from_session is called, but session[:user_id] is nil, so nil is returned.
- login_from_basic_auth is called, and username:password is present, so the corresponding user is returned.
- The user is considered authenticated.
Here is a more detailed authentication lifecycle (remember me cookie):
- A user has previously logged in and chosen the 'remember me' option.
- A user closes their browser and then re-opens it and visits your site.
- login_from_session is called, but session[:user_id] is nil, so nil is returned.
- login_from_basic_auth is called, but username and password are missing, so nil is returned.
- login_from_cookie is called and a cookie is found and used to return a user.
- The user is considered authenticated.
精彩评论