22

ユーザーのログインとパスワードが正しく送信された後にユーザー情報を取得できる基本的な API を構築しています。

現在、私は次のようなものを使用しています:

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

したがって、私がする必要があるのは、リクエストで送信されたユーザー/パスワード (fooおよびbar) にアクセスすることですが、Rails コントローラーでその情報にアクセスする方法がわかりません。

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 looking at this at the completely wrong way, but that's where I'm at right now. :)

4

2 に答える 2

52

リクエストから資格情報を取得する方法に関する質問への答えは次のとおりです。

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

ただし、基本認証を行うために必要なのは、authenticate_or_request_with_http_basic だけです。

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 は 401 ステータスを返し、ブラウザにユーザー名/パスワード ダイアログが表示されます。詳細が指定されている場合、それらは指定されたブロックに渡されます。ブロックが true を返す場合、リクエストは通過します。それ以外の場合、リクエスト処理は中止され、403 ステータスがクライアントに返されます。

また、Railscast 82 をチェックアウトすることもできます (上記のコードはそこからのものです): http://railscasts.com/episodes/82-http-basic-authentication

于 2010-03-10T01:26:50.483 に答える
1

Rails プラグインのAuthlogicは、この機能 (およびその他の機能) をすぐにサポートします。そのソースを探し回ったり、単に既存のアプリケーションに統合したりすることができます。

編集:
Authlogicのソースコードを掘り下げた後、次のコードを使用してユーザー名とパスワードを取得するこのファイルを見つけました:

  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

私はそれがどこに行くのかをもう少し詳しく調べたいと思いますが、私は寝なければなりません. お役に立てば幸いです。

于 2010-03-08T06:01:08.893 に答える