ruby-on-rails - 这个 Rails JSON 身份验证 API(使用 Devise)安全吗?

标签 ruby-on-rails json api security devise

我的 Rails 应用使用 Devise 进行身份验证。它有一个姊妹 iOS 应用程序,用户可以使用与 Web 应用程序相同的凭据登录到 iOS 应用程序。所以我需要某种 API 来进行身份验证。

这里有很多类似的问题指向this tutorial ,但它似乎已过时,如 token_authenticatable模块已从设计中删除,并且一些行抛出错误。 (我使用的是 Devise 3.2.2。)我尝试根据该教程(和 this one )推出自己的版本,但我对它不是 100% 有信心 - 我觉得我可能有一些东西被误解或错过了。

首先,听从this gist的建议,我添加了一个 authentication_token我的 users 的文本属性表,以及以下到 user.rb :

before_save :ensure_authentication_token

def ensure_authentication_token
  if authentication_token.blank?
    self.authentication_token = generate_authentication_token
  end
end

private

  def generate_authentication_token
    loop do
      token = Devise.friendly_token
      break token unless User.find_by(authentication_token: token)
    end
  end

然后我有以下 Controller :

api_controller.rb

class ApiController < ApplicationController
  respond_to :json
  skip_before_filter :authenticate_user!

  protected

  def user_params
    params[:user].permit(:email, :password, :password_confirmation)
  end
end

(请注意,我的 application_controllerbefore_filter :authenticate_user! 行。)

api/sessions_controller.rb

class Api::SessionsController < Devise::RegistrationsController
  prepend_before_filter :require_no_authentication, :only => [:create ]

  before_filter :ensure_params_exist

  respond_to :json

  skip_before_filter :verify_authenticity_token

  def create
    build_resource
    resource = User.find_for_database_authentication(
      email: params[:user][:email]
    )
    return invalid_login_attempt unless resource

    if resource.valid_password?(params[:user][:password])
      sign_in("user", resource)
      render json: {
        success: true,
        auth_token: resource.authentication_token,
        email: resource.email
      }
      return
    end
    invalid_login_attempt
  end

  def destroy
    sign_out(resource_name)
  end

  protected

    def ensure_params_exist
      return unless params[:user].blank?
      render json: {
        success: false,
        message: "missing user parameter"
      }, status: 422
    end

    def invalid_login_attempt
      warden.custom_failure!
      render json: {
        success: false,
        message: "Error with your login or password"
      }, status: 401
    end
end

api/registrations_controller.rb

class Api::RegistrationsController < ApiController
  skip_before_filter :verify_authenticity_token

  def create
    user = User.new(user_params)
    if user.save
      render(
        json: Jbuilder.encode do |j|
          j.success true
          j.email user.email
          j.auth_token user.authentication_token
        end,
        status: 201
      )
      return
    else
      warden.custom_failure!
      render json: user.errors, status: 422
    end
  end
end

config/routes.rb 中:

  namespace :api, defaults: { format: "json" } do
    devise_for :users
  end

我有点不知所措,但我敢肯定,我 future 的自己会在这里回顾和畏缩(通常是这样)。一些不确定的部分:

首先,您会注意到 Api::SessionsController继承自 Devise::RegistrationsControllerApi::RegistrationsController继承自 ApiController (我还有一些其他 Controller ,例如 Api::EventsController < ApiController,它们为我的其他模型处理更多标准 REST 内容,并且与 Devise 没有太多联系。)这是一个非常丑陋的安排,但我想不出另一种方法在 Api::RegistrationsController 中获取我需要的方法.我上面链接的教程有 include Devise::Controllers::InternalHelpers 行,但该模块似乎已在较新版本的 Devise 中被删除。

其次,我已通过 skip_before_filter :verify_authentication_token 行禁用了 CSRF 保护。 .我怀疑这是否是个好主意 - 我看到很多 conflictinghard to understand关于 JSON API 是否容易受到 CSRF 攻击的建议 - 但添加该行是我可以让该死的东西工作的唯一方法。

第三,我想确保了解用户登录后身份验证的工作原理。假设我有一个 API 调用 GET /api/friends它返回当前用户的 friend 列表。据我了解,iOS 应用程序必须获取用户的 authentication_token从数据库中(对于每个用户来说这是一个永远不会改变的固定值??),然后将其作为参数与每个请求一起提交,例如GET /api/friends?authentication_token=abcdefgh1234 ,然后我的Api::FriendsController可以做一些像 User.find_by(authentication_token: params[:authentication_token])获取 current_user。真的这么简单,还是我遗漏了什么?

因此,对于任何设法一直阅读到这个庞大问题结尾的人,感谢您的宝贵时间!总结一下:

  1. 这个登录系统安全吗? 或者有什么我忽略或误解的东西,例如当涉及到 CSRF 攻击?
  2. 我对用户登录后如何验证请求的理解是否正确?(请参阅上面的“第三个...”。)
  3. 有什么办法可以清理或改进这段代码吗? 特别是让一个 Controller 继承自 Devise::RegistrationsController 的丑陋设计以及来自 ApiController 的其他人.

谢谢!

最佳答案

您不想禁用 CSRF,我读到人们认为出于某种原因它不适用于 JSON API,但这是一种误解。要使其保持启用状态,您需要进行一些更改:

  • 在服务器端添加一个 after_filter 到你的 session Controller :

    after_filter :set_csrf_header, only: [:new, :create]
    
    protected
    
    def set_csrf_header
       response.headers['X-CSRF-Token'] = form_authenticity_token
    end
    

    这将生成一个 token ,将其放入您的 session 中并将其复制到所选操作的响应 header 中。

  • 客户端 (iOS) 你需要确保两件事情就位。

    • 您的客户端需要扫描此 header 的所有服务器响应并在传递时保留它。

      ... get ahold of response object
      // response may be a NSURLResponse object, so convert:
      NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
      // grab token if present, make sure you have a config object to store it in
      NSString *token = [[httpResponse allHeaderFields] objectForKey:@"X-CSRF-Token"];
      if (token)
         [yourConfig setCsrfToken:token];
      
    • 最后,您的客户端需要将此 token 添加到它发出的所有“非 GET”请求中:

      ... get ahold of your request object
      if (yourConfig.csrfToken && ![request.httpMethod isEqualToString:@"GET"])
        [request setValue:yourConfig.csrfToken forHTTPHeaderField:@"X-CSRF-Token"];
      

最后一个难题是要了解当登录到设计时,正在使用两个后续 session /csrf token 。登录流程如下所示:

GET /users/sign_in ->
  // new action is called, initial token is set
  // now send login form on callback:
  POST /users/sign_in <username, password> ->
    // create action called, token is reset
    // when login is successful, session and token are replaced 
    // and you can send authenticated requests

关于ruby-on-rails - 这个 Rails JSON 身份验证 API(使用 Devise)安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20745843/

相关文章:

mysql - 如何使模型指向非默认模式

ruby-on-rails - 如何让 Vanity 连接到 Elasticache 实例

javascript - 获取 api,为什么我必须在响应 json() 上使用 then,试图使 promise 有意义

java - 将 Bean/ResultSet 写入 CSV 文件的已知 API

json - RESTful 集合资源 - 惯用的 JSON 表示和往返

ruby-on-rails - 如何遍历 JSON 数组以获取键的值?

ruby-on-rails - View 和 Controller 外部的 Rails Engine RouteProxy

json - 如何在 sails-mongo 中添加 json 对象作为属性类型

java - 如何在Spring Boot中从另一个集合获取数据

ruby-on-rails - 将 rails 限制为仅响应 JSON 和 XML 请求