Home Contact Sitemap

Preston Lee

Founder, CEO, OpenRain.com

About

During the day I run OpenRain in Phoenix: a Ruby on Rails development shop. During the night... well... I still have to run OpenRain, but when I find time to breathe, I exhale here. If you'd like to get in touch professionally, don't hesitate to contact me via the OpenRain website.

Peace,

Preston

Rails 2.0: HTTP Basic Authentication

lock.pngHTTP Basic authentication support comes bundled with Rails 2.0, alleviating the need for external plugins we used with Rails 1.x. Here’s how you can use (and test) this new Rails 2.0 feature.Controller Code

before_filter :authenticatedef authenticate

authenticate_or_request_with_http_basic do |username, password|

true # replace with your own custom logic

end

end

Functional Test

def setup

@controller = AdminController.new
@request = ActionController::TestRequest.new

@response = ActionController::TestResponse.new

set_basic_authentication

end

def test_basic_authentication_success

get :index
assert_response :success

end

def set_basic_authentication

@request.env['HTTP_AUTHORIZATION'] = ‘Basic ‘ + Base64::b64encode(”some_username:some_password”)

end

For Rails 2.0 internal implementation details, see http_authentication.rb.

Share/Save/Bookmark

Tags: , ,

. 26 Dec 07 | Computer


Reader's Comments

  1. ryan |

    Where does “Configuration::ADMIN[:username]” come from?

  2. preston.lee |

    Just a placeholder for wherever your admin password comes from. I updated it to read “some_username:some_password”.

  3. Anthony Bailey |

    Thanks for this - just what I was Googling for.

    BTW, I found that Base64::b64encode printed the encoded string as a side effect, which made my rake test output rather noisy.

    Using Base64::encode64 instead solved that for me.



Leave a Reply