开发者

In Ruby on Rails, what does authenticate_with_http_basic do?

开发者 https://www.devze.com 2023-02-13 06:33 出处:网络
Restful Authentication us开发者_StackOverflow中文版es authenticate_with_http_basic, but a search on the net can find many pages with no description.On the official http://api.rubyonrails.org/, it can

Restful Authentication us开发者_StackOverflow中文版es authenticate_with_http_basic, but a search on the net can find many pages with no description. On the official http://api.rubyonrails.org/, it can also be found, except again there is no description, no comment, no spec.

What does it do? it seems to be able to use a login_name and password from an HTTP request and then they can be compared to the login_name and encrypted_password in the users table... but is that the case, why aren't there even a 1-line description?


This method allows you to implement basic http authentication (the kind where a little dialog box pops up asking for a username and password). It's generally a great way to limit access to a development site or admin area. For example:

class AdminController < ApplicationController
  before_filter :authenticate

  def authenticate
    authenticate_or_request_with_http_basic('Administration') do |username, password|
      username == 'admin' && password == 'password'
    end
  end
end

This function will either make a request for the basic http authentication username and password, or after it has been entered, it will actually check if the authentication was correct. In other words this function will either call authenticate_with_http_basic or it will call request_http_basic_authentication. You can read more about it and see more examples here. You'll generally call authenticate_or_request_with_http_basic instead of calling authenticate_with_http_basic or request_http_basic_authentication, since the former function will all the appropriate of the latter functions.

P.S: authenticate_with_http_basic does not use POST variables, it uses header information to get the username and password (request.env['HTTP_AUTHORIZATION']). You can view more information about the authorization function here.


Some details that would have saved me time if I could read them anywhere.

I fiddled with it. authenticate_with_http_basic just reads basic-auth user/pass from request and executes inner block when such info is present in the request. If no auth is sent by client, it returns nil. Otherwise it returns whatever the block evaluates to.

So you can use return value to decide whether to do request_http_basic_authentication, return 403 forbidden or render content.

FYI, if you are running this from a method registered as a before_action hook, I noticed that return value of that method is disregarded. In case method rendered something or redirected, the action is not executed. If the method does not render or redirect, then action is executed.

HTH (talking about Rails 5 to be clear)

0

精彩评论

暂无评论...
验证码 换一张
取 消