authenticate_or_request_with_http_token返回html而不是json

Fed*_*ria 16 json ruby-on-rails rails-api

我已经创建了一个rails-api应用程序并继续使用令牌认证来保护它.

我设置了一个before_filter调用使用的方法authenticate_or_request_with_http_token.一切正常,但是,当身份验证不正确时,我得到一个HTML响应.

如何定义响应的格式?

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
Run Code Online (Sandbox Code Playgroud)

ber*_*kes 31

通过包括ActionController::HttpAuthentication::Token::ControllerMethods你包括几个方法,其中request_http_token_authentication只是一个包装Token.authentication_request.那个#authentication_request方法是罪魁祸首,并发送纯文本(不是你的问题建议的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
Run Code Online (Sandbox Code Playgroud)

诀窍是覆盖request_http_token_authenticationApplicationController调用,Token.authentication_request但设置正确的状态和标题然后再渲染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
Run Code Online (Sandbox Code Playgroud)

  • 目前,您必须将此函数定义为`request_http_token_authentication(realm ='Application',message = nil)`. (4认同)