17

我想使用rails-api gem special 来创建仅限 API 的应用程序。为了提供身份验证机制,我想使用Railscasts #352中描述的内置authenticate_or_request_with_http_token方法,但这里缺少此方法。

有人有使用rails-api gem 的经验吗?

PS我可以看到这种方法,但这是否可以投入生产?

4

2 回答 2

49

我正在使用 rails-api 开发服务。我们还没有部署,但已经接近那个时间,并且在测试中没有任何问题。您需要包含您想要使用的任何非必要模块,因为 rails-api 已被向下修剪。我在 ApplicationController 中使用 authenticate_or_request_with_http_token ,如下所示:

include ActionController::HttpAuthentication::Token::ControllerMethods

def authenticate
  authenticate_or_request_with_http_token do |token, options|
    apiKey = ApiKey.where(auth_token: token).first
    @current_user = apiKey.user if apiKey
  end
end 

如果你只想要令牌,有一个方便的方法 token_and_options:

include ActionController::HttpAuthentication::Token

def current_user
  api_key = ApiKey.where(auth_token: token_and_options(request)).first
  User.find(api_key.user_id) if api_key
end
于 2012-07-02T19:27:48.327 回答
2

自述文件

基本、摘要和令牌身份验证:Rails 提供了对三种 HTTP 身份验证的开箱即用支持。

所以,是的,这是生产就绪的(毕竟它仍然是 Rails)。您链接到的示例是要走的路(诀窍是只包含您需要的 Action Pack)。

于 2012-06-27T15:37:53.950 回答