Rails authenticate_or_request_with_http_basic

in my RoR application, I need to protect a page with basic authentication, and I want credentials to be requested every time a user links to this page.

so I added a filter before the operation, for example:

before_filter :request_confirm, :only => [:delete_device] 

and filter method:

 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 

this is normal, but only for the first time, because the rails save the inserted data, so the next time the filter will be executed, but the credentials will not be requested.

I do not know where the credentials are stored. ,

+4
source share
1 answer

Here's how the authenticate_or_request_with_http_basic method and how HTTP authentication works in general. authenticate_or_request_with_http_basic can be changed as follows: "First try to authenticate and, if not authenticate, an authentication request." The source code for 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's going on. When you first type the URL that causes this action, this authenticate_or_request_with_http_basic returns an HTTP 401 Unauthorized response. The browser understands that this is an authentication request and shows you a dialog for entering a username and password, and then resends the request to the same URL, but includes your credentials in the request headers. The filter strikes again, and this authenticate_or_request_with_http_basic time method sees that the request has authentication headers and successfully resolves you. And the browser will send these auth headers for each subsequent request to this domain (until you close the browser).

So, if you just need to check it several times, you can close and reopen the browser. I believe that using only these methods, it is not possible to request authentication and authentication with each request, because when an application receives a request from a browser with Auth headers, it cannot determine whether it is a request immediately after an authentication request, or is it earlier saved headers.

But this can be achieved in some way using cookies or values ​​stored in the session.

+4
source

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


All Articles