簡體   English   中英

這個Rails JSON身份驗證API(使用Devise)是否安全?

[英]Is this Rails JSON authentication API (using Devise) secure?

我的Rails應用程序使用Devise進行身份驗證。 它有一個姐妹iOS應用程序,用戶可以使用與Web應用程序相同的憑據登錄到iOS應用程序。 所以我需要某種API進行身份驗證。

這里有許多類似的問題指向本教程 ,但它似乎已過時,因為從Devise中刪除了token_authenticatable模塊,並且其中一些行引發了錯誤。 (我使用的是Devise 3.2.2。)我曾嘗試根據該教程(和教程)來推出自己的教程,但我對此並不100%自信-我覺得可能有些東西被誤解或錯過。

首先,按照本要點的建議,我向users表添加了authentication_token文本屬性,並向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

然后,我有以下控制器:

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_controller中的代碼行before_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

我有點不合常理,而且我確定這里有些東西會讓我未來的自我回顧並畏縮(通常是這樣)。 一些困難的部分:

首先 ,您會注意到Api::SessionsController繼承自Devise::RegistrationsControllerApi::RegistrationsController繼承自ApiController (我還有其他一些控制器,例如Api::EventsController < ApiController ,它可以處理其他我更多的標准REST東西模型,並且與Devise沒有太多聯系。)這是一個非常丑陋的安排,但我想不出另一種方法來訪問Api::RegistrationsController所需的方法。 我上面鏈接的教程的行include Devise::Controllers::InternalHelpers ,但是該模塊似乎已在Devise的最新版本中刪除。

其次 ,我已使用skip_before_filter :verify_authentication_token行禁用了CSRF保護。 我對這是否是一個好主意感到懷疑-我看到關於JSON API是否易受CSRF攻擊的很多沖突難以理解的建議-但添加這行是我可以使該死的事情起作用的唯一方法。

第三 ,我想確保我了解用戶登錄后身份驗證的工作原理。假設我有一個API調用GET /api/friends ,該API返回當前用戶的朋友列表。 據我了解,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. 有什么辦法可以清除或改進此代碼? 特別是讓一個控制器從Devise::RegistrationsController繼承而另一個從ApiController繼承的丑陋設計。

謝謝!

您不想禁用CSRF,我已經讀到人們認為出於某種原因它不適用於JSON API,但這是一種誤解。 要使其保持啟用狀態,您需要進行一些更改:

  • 在服務器端,將一個after_filter添加到您的會話控制器中:

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

    這將生成一個令牌,將其放入您的會話中,然后將其復制到所選操作的響應標頭中。

  • 客戶端(iOS),您需要確保已完成兩件事。

    • 您的客戶端需要掃描所有服務器響應以查找此標頭,並在傳遞時保留它。

       ... 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]; 
    • 最后,您的客戶需要將此令牌添加到它發出的所有“非GET”請求中:

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

最后一個難題是要了解,在登錄進行設計時,正在使用兩個后續的session / csrf令牌。 登錄流程如下所示:

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

你的例子似乎模仿從設計博客的代碼- https://gist.github.com/josevalim/fb706b1e933ef01e4fb6

如該帖子所述,您的操作類似於選項1,他們說這是不安全的選項。 我認為關鍵是您不想每次保存用戶時都簡單地重置身份驗證令牌。 我認為令牌應顯式創建(通過API中的某種TokenController)並應定期過期。

您會注意到我說“我認為”,因為(據我所知)沒有人對此有更多信息。

OWASP Top 10中記錄了Web應用程序中最常見的10個最常見的漏洞。 這個問題提到跨站請求偽造(CSRF)保護已禁用,並且CSRF處於OWASDP前10名中 簡而言之,攻擊者使用CSRF以經過身份驗證的用戶身份執行操作。 禁用CSRF保護將導致應用程序中的高風險漏洞,並破壞擁有安全身份驗證系統的目的。 CSRF保護失敗的原因很可能是因為客戶端無法傳遞CSRF同步令牌。

閱讀整個OWASP前10名,否則將非常危險 密切關注斷開的身份驗證和會話管理 ,並查看會話管理備忘單

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM