通过标头令牌进行rails-api认证

Ana*_*oly 15 authentication ruby-on-rails rails-api

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

有没有人对rails-api gem 有经验?

PS我可以看到这种方法,但是这个生产准备好了吗?

小智 48

我正在使用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 
Run Code Online (Sandbox Code Playgroud)

如果您只想要令牌,那么有一个方便的方法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
Run Code Online (Sandbox Code Playgroud)