2013-07-18 36 views
15

私はrails-apiアプリケーションを作成し、トークン認証を使用してそのセキュリティを確保しました。authenticate_or_request_with_http_tokenがjsonの代わりにhtmlを返す

authenticate_or_request_with_http_tokenを使用するメソッドを呼び出すbefore_filterを設定しました。すべて正常に動作していますが、認証が正しくない場合、私はHTMLの応答を得ています。

レスポンスの形式はどのように定義できますか?あなたは、単にToken.authentication_requestのラッパーである他人request_http_token_authenticationの中でいくつかの方法が含まれるActionController::HttpAuthentication::Token::ControllerMethods含むことで

before_filter :restrict_access 

private 

def restrict_access 
    authenticate_or_request_with_http_token do |token, options| 
    check_token token 
    end 
end 

def check_token(token) 
    Session.exists?(access_token: token) 
end 
+1

あなたのコードをいくつか表示して、人々が実際に助けることができますか? – GoGoGarrett

+0

@GoGoGarrettが私の質問を更新しました。 –

答えて

28

。それ#authentication_request -methodが犯人であると次のようにプレーンテキスト(ご質問の通りではないHTML)を送信します。

def authentication_request(controller, realm) 
    controller.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}") 
    controller.__send__ :render, :text => "HTTP Token: Access denied.\n", :status => :unauthorized 
end 

トリックはあなたのApplicationControllerないへの呼び出しToken.authentication_requestrequest_http_token_authenticationを上書きするのではなく、正しいを設定することですステータスとヘッダーを取得し、代わりにJSONを表示します。これをあなたのApplicationControllerに追加してください:

protected 
def request_http_token_authentication(realm = "Application") 
    self.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}") 
    render :json => {:error => "HTTP Token: Access denied."}, :status => :unauthorized 
end 
+2

現在、この関数を 'request_http_token_authentication(realm = 'Application'、message = nil)'と定義する必要があります。 –

+0

"現在"では、Railsエッジ、@DiegoCoutoを意味しますか? – berkes

+1

これは正しい@berkesです! [見てください](https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/http_authentication.rb#L422)。それを指摘してくれてありがとう、BTW。 :-) –

関連する問題