【问题标题】:Best way to test user authentication for APIs?测试 API 用户身份验证的最佳方法?
【发布时间】:2016-09-24 23:34:28
【问题描述】:

我正在使用 Ruby on Rails 构建 API,并(尝试)使用名为 Devise Token Auth 的 gem 构建用户身份验证。但我不确定在每个控制器操作之前验证/验证用户的最佳方法。

我知道before_action :authenitcate_user! 呼叫,但它认为我的用户没有登录,因为我从外部客户端拨打电话。

我是否需要将其他参数与我没有考虑的请求一起传递?比如令牌或会话 ID?

【问题讨论】:

    标签: ruby-on-rails ruby authentication devise token


    【解决方案1】:

    尝试 simple_token_authentication https://github.com/gonzalo-bulnes/simple_token_authentication 与 Devise 一起使用,并且易于集成。 您只需发送用户身份验证令牌和电子邮件,即可执行身份验证。

    【讨论】:

    • 这与设计令牌身份验证有何不同?它如何解决我在每个控制器操作之前对用户进行身份验证的问题?
    • 您好,如果您正在构建 API,则必须将每个请求的身份验证参数发送到您的服务器,此 gem 会验证包含 的每个控制器上的参数(默认为电子邮件和令牌) acts_as_token_authentication_handler_for User,你也可以acts_as_token_authentication_handler_for User,只有:[:method1, :method2]
    【解决方案2】:

    如果您正在构建轻量级 API 应用程序,我会考虑使用 Knock

    Devise 是传统应用程序的绝佳解决方案,在这些应用程序中,您需要一个完整的身份验证解决方案,包括注册、密码编辑等。但它是围绕基于会话的身份验证设计的,并且由于可用的自定义数量众多,代码库有点像怪物 -使用基于令牌的身份验证,您只会使用其中的 1%。

    基本设置是:

    class ApplicationController < ActionController::API
      include Knock::Authenticable
      prepend_before_action :authenticate_user
    end
    

    现在,如果我们发送一个没有有效 Authorization: Bearer SOME_TOKEN 标头的请求,Knock 将返回一个 401 - Unauthorized 响应。

    我们可以这样测试:

    class UsersControllerTest < ActionDispatch::IntegrationTest
      def token
        Knock::AuthToken.new(payload: { sub: users(:one).id }).token
      end
    
      it 'does not allow an unauthenicated request' do
        get users_path
        assert_response :unauthorized
      end
    
      it 'allow an authenicated request' do
        get users_path, headers: { authorization: "Bearer #{token}" }
        assert_response :success
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2015-04-23
      • 2013-08-27
      • 1970-01-01
      • 2017-09-03
      • 1970-01-01
      • 1970-01-01
      • 2015-07-14
      • 2020-10-12
      • 2011-04-29
      相关资源
      最近更新 更多