当前位置: 首页 > 面试题库 >

这个Rails JSON身份验证API(使用Devise)是否安全?

柯唯
2023-03-14
问题内容

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

这里有许多类似的问题指向本教程,但它似乎token_authenticatable已过时,因为此模块已从Devise中删除,并且某些行会引发错误。(我使用的是Devise
3.2.2。)我曾尝试根据该教程(和本教程)推出自己的教程,但我对此并不百分百自信-
我觉得可能有些东西被误解或错过。

首先,按照这个要点的建议,我authentication_tokenusers表中添加了text属性,以下内容添加到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::SessionsControllerfrom的继承,Devise::RegistrationsController而from的Api::RegistrationsController继承ApiController(我还有其他一些控制器,例如Api::EventsController < ApiController用于处理其他模型的更多标准REST东西,而与Devise的联系并不多。)这是一个非常丑陋的安排,但我想不出另一种方法来访问所需的方法Api::RegistrationsController。我上面链接的教程的内容是include Devise::Controllers::InternalHelpers,但此模块似乎已在Devise的最新版本中删除。

其次 ,我禁用了该线路的CSRF保护skip_before_filter :verify_authentication_token。我对这是否是一个好主意感到怀疑-我看到关于JSON
API是否易受CSRF攻击的许多冲突或难以理解的建议-但添加这一行是我使该死的事情起作用的唯一方法。

第三 ,我想确保我了解用户登录后身份验证的工作原理。假设我有一个API调用GET /api/friends,该调用返回了当前用户的朋友列表。据我了解,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


 类似资料:
  • 问题内容: 我正在开发一个RailsWeb应用程序,该应用程序还为移动设备提供了基于JSON的API。移动客户端应首先通过(电子邮件/通过)获得令牌,然后客户端将使用该令牌进行后续的API调用。 我对Devise相当陌生,我正在寻找一个Devise API外观,并希望它返回true / false,然后基于此,我将创建并返回令牌或返回拒绝消息。但似乎Devise没有提供类似的信息。 我知道Devi

  • 本文向大家介绍Ruby on Rails 使用Devise进行身份验证,包括了Ruby on Rails 使用Devise进行身份验证的使用技巧和注意事项,需要的朋友参考一下 示例 将gem添加到Gemfile中: gem 'devise' 然后运行bundle install命令。 使用命令$rails generate devise:install生成所需的配置文件。 在每个环境中为Devis

  • 问题内容: 我正在使用Rails做一个单页应用程序。登录和注销时,使用ajax调用Devise控制器。我遇到的问题是当我1)登录2)退出然后再次登录时不起作用。 我认为这与CSRF令牌有关,该令牌在我退出时会重置(尽管它不应该出现),并且由于它是单页的,因此在xhr请求中发送了旧的CSRF令牌,从而重置了会话。 更具体地说,这是工作流程: 登入 登出 登录(成功201。但是在服务器日志中打印) 后

  • 我正在尝试使用一个Gem devise-two-factor在Devise上实现双因素身份验证。我想验证是在2个步骤,在第一,我将要求用户名和密码。如果用户通过了这一步,那么他将被重定向到OTP的下一页,如果2FA被激活,否则会话将由Devise验证。 如果用户选择了2fa,那么我希望使用Devise来执行所有的身份验证,而不希望在User.validate_and_consume_otp(CUR

  • 我想解释一个认证流程,并希望你能回答,如果亚马逊认知的正确解决方案。 要求:对于每个登录(用户名/密码、Facebook、Google等),都应该有一个有效的用户池帐户。 Flow Facebook(不存在身份或用户池帐户)。 客户点击“使用Facebook登录”: 1) 调用GetOpenIdToken- 1a)同时,使用FB AccessToken从Facebook获取电子邮件地址 2)使用生

  • 问题内容: 几个不同的问题和一些不同的教程中都涉及到了这一点,但是我所遇到的所有以前的资源并没有完全解决问题。 简而言之,我需要 通过POST从登录到 为用户提供提供路由的“已登录” GUI /组件状态 用户注销/注销时能够“更新” UI。 这是最令人沮丧的 保护我的路由以检查身份验证状态(他们是否需要),并将用户相应地重定向到登录页面 我的问题是 每次导航到另一个页面时,我都需要打电话以确定用户