简体   繁体   English

测试API用户身份验证的最佳方法?

[英]Best way to test user authentication for APIs?

I'm building an API with Ruby on Rails and (attempting to) build user auth with a gem called Devise Token Auth. 我正在使用Ruby on Rails构建API,并(尝试)使用名为Devise Token Auth的gem来构建用户身份验证。 But I'm uncertain about the best way to validate / authenticate a user before each controller action. 但是我不确定在每次控制器操作之前验证/验证用户的最佳方法。

I know of the before_action :authenitcate_user! 我知道before_action :authenitcate_user! call but it thinks my users aren't signed in since I'm making calls from an external client. 电话,但它认为我的用户未登录,因为我正在从外部客户端拨打电话。

Do I need to pass other arguments along with my requests that I'm not thinking of? 我是否需要传递其他我不认为有必要的论点? Like a token or session id? 像令牌或会话ID?

try simple_token_authentication https://github.com/gonzalo-bulnes/simple_token_authentication works with Devise and is easy to integrate. 尝试simple_token_authentication https://github.com/gonzalo-bulnes/simple_token_authentication可与Devise一起使用,并且易于集成。 You just need to send the user authentication token and email, to perform the authentication. 您只需要发送用户身份验证令牌和电子邮件,即可执行身份验证。

If you are building a lightweight API app I would consider using Knock . 如果您要构建轻量级的API应用程序,则可以考虑使用Knock

Devise is a great solution for traditional apps where you need a full authentication solution with signups, password editing etc. But it is designed around session based authentication and the codebase is somewhat of a monster due to the crazy amount of customizations available - with token based auth you will only be using about 1% of it. Devise是传统应用程序的理想解决方案,在传统应用程序中,您需要具有注册,密码编辑等功能的完整身份验证解决方案。但是,它是基于基于会话的身份验证而设计的,由于可定制的数量惊人(基于令牌),因此代码库有些怪异验证,您将只使用其中的1%。

A basic setup would be: 基本设置为:

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

Now if we send a request without a valid Authorization: Bearer SOME_TOKEN header Knock will return a 401 - Unauthorized response. 现在,如果我们发送的请求没有有效的Authorization: Bearer SOME_TOKEN标头Knock将返回401 - Unauthorized响应。

We can test it like so: 我们可以像这样测试它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM