开发者

Rails: Accessing the username/password used for HTTP Basic Auth?

开发者 https://www.devze.com 2022-12-22 00:56 出处:网络
I\'m building a basic API where user information can be retrieved after that user\'s login and password are correctly sent.

I'm building a basic API where user information can be retrieved after that user's login and password are correctly sent.

Right now I'm using something like this:

http://foo:bar@example.com/api/user.xml

So, what I need to do is access the user/password sent in the request (the foo and bar) but am not sure how to access that info in a Rails controller.

Then I'd check those variables via a quick User.find and then set those as the username and password variables for authenticate_or_request_with_http_basic.

It's possible I'm l开发者_如何学Pythonooking at this at the completely wrong way, but that's where I'm at right now. :)


The answer to your question of how to get the credentials from the request is this:

user, pass = ActionController::HttpAuthentication::Basic::user_name_and_password(request)

However authenticate_or_request_with_http_basic is all you need to do basic auth:

class BlahController < ApplicationController
  before_filter :authenticate

  protected

  def authenticate
    authenticate_or_request_with_http_basic do |username, password|
      # you probably want to guard against a wrong username, and encrypt the
      # password but this is the idea.
      User.find_by_name(username).password == password
    end
  end
end

authenticate_or_request_with_http_basic will return a 401 status if credentials are not supplied, which will pop up the username/password dialog in a browser. If details are given then those are passed to the block provided. If the block returns true the request goes through. Otherwise the request processing is aborted and a 403 status is returned to the client.

You can also check out Railscast 82 (thats were the code above is from): http://railscasts.com/episodes/82-http-basic-authentication


The rails plugin Authlogic supports this functionality (as well as much more) out of the box. You could root around in the source for it, or simply integrate it into your existing application.

Edit:
After digging around the source code for Authlogic, I found this file which uses the following piece of code to grab the username and password:

  def authenticate_with_http_basic(&block)
    @auth = Rack::Auth::Basic::Request.new(controller.request.env)
    if @auth.provided? and @auth.basic?
      block.call(*@auth.credentials)
    else
      false
    end
  end

I'd look a bit further into where it all goes, but I've got to get to bed. Hope I was of some help.

0

精彩评论

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

关注公众号