in my RoR application i need to protect a page with basic authentication and i want that the credentials are asked every time that a user link to that page.
so i added a filter before the operation, like this:
before_filter :request_confirm, :only => [:delete_device]
and the filter method is:
def request_confirm
user = User.find_by_id(session[:user_id])
authenticate_or_request_with_http_basic do |nick, pass|
nick == user.nickname and pass == user.password
end
end
it's ok, but only the first time because rails save inserted data, so the following times the filter will be execute but the credential won't ask.
I don't know where credential are saved. .
This is how method authenticate_or_request_with_http_basic
and in general how HTTP authentication works. authenticate_or_request_with_http_basic
can be reworded as: "First try to authenticate and if not authenticated, request for authentication". The source code of this method is as follows:
def authenticate_or_request_with_http_basic(realm = "Application", &login_procedure)
authenticate_with_http_basic(&login_procedure) || request_http_basic_authentication(realm)
end
So what happens. When you first hit the URL that invokes this action, this authenticate_or_request_with_http_basic
returns HTTP response 401 Unauthorized. The browser understands this is a request for authentication and shows you a dialog to enter username and password, and then resends the request for the same URL but includes your credentials into request headers. You filter is hit again, and this time method authenticate_or_request_with_http_basic
sees that there are authentication headers in the request and authorises you successfully. And the browser will send these auth headers on each following request to this domain (until you close the browser).
So if you need just test it several times you can close and reopen browser. I believe using only these methods it is impossible to ask for authentication and authenticate on every request because when the application gets request from browser with Auth headers it can not tell whether this is request immediately after authentication request, or these are headers preserved before.
But this can be somehow accomplished using cookies or value stored in session.
来源:https://stackoverflow.com/questions/12479251/rails-authenticate-or-request-with-http-basic