为 webapp 和 api 使用 devise_token_auth 库

Using devise_token_auth library for both webapp and api

我正在使用 devise_token_auth(https://github.com/lynndylanhurley/devise_token_auth) 来验证移动设备,我还需要为我的网络应用程序使用设计。

问题是用户可以通过 devise_token_auth 注册,但如果用户登录并尝试调用包含“before_action :authenticate_user!”的控制器中的特定函数,我会收到一条错误消息Authorized Users Only.

想知道有没有办法把devisedevise_token_auth一起使用

代码:

class RestrictedController < ApplicationController
  before_action :authenticate_user!

  def stuff
    head :ok
  end
end

首先,您应该知道 devise 不再管理用户的 session。这就是为什么建议使用 devise_token_auth.

每当您在控制器上指定 before_action :authenticate_user! 时,所有操作(如 RestrictedController#stuff)都需要用户登录。devise_token_auth 期望在查询中收到 header 下面列出了 4 个参数。

这是您需要做的:

  1. 使用 devise_token_auth 提供的路线登录。
  2. 如果登录成功,您将在 header 中收到一个 access-token、一个 client、一个 token-type 和一个 uid
  3. 每当您想 运行 控制器操作时,用户必须登录,请在查询 headers 中指定 access-tokenclienttoken-typeuid