新手问题 使用 Devise Token 认证,登录被拦截,

msms · November 08, 2019 · Last by tinyfeng replied at November 11, 2019 · 2536 hits

问题:在使用 Devise Token 用户登录认证时,登录之前被拦截了。还是说 Devise 的 before_action :authenticate_sys_user!会把 Devise 自带的 action 都给拦截了?

代码信息

class ApplicationController < ActionController::API

    include DeviseTokenAuth::Concerns::SetUserByToken

    before_action :authenticate_sys_user!

    respond_to :json
end

Gem 文件

gem "devise"
gem "devise-encryptable"
gem 'devise_token_auth'

routes 文件

resources :sys_users

mount_devise_token_auth_for "SysUser", at: 'auth'

日志信息:

Started POST "/auth/sign_in" for ::1 at 2019-11-08 09:50:01 +0800
Processing by DeviseTokenAuth::SessionsController#create as JSON
  Parameters: {"email"=>"[email protected]", "password"=>"[FILTERED]", "session"=>{"email"=>"[email protected]", "password"=>"[FILTERED]"}}
Filter chain halted as :authenticate_sys_user! rendered or redirected
Completed 401 Unauthorized in 1ms (Views: 0.2ms | ActiveRecord: 0.0ms | Allocations: 163)

authenticate_sys_user! 是 devise 提供的,但 before_action 是 Rails 的。因为 ApplicationController 基本上是所有 controller 的超类,所以 DeviseTokenAuth::SessionsController#create 受影响其实很正常。

Devise 自己的登录、注册的 controller 应该不会不拦截吧,不知道是不是受到这个 Gem 的影响 https://github.com/lynndylanhurley/devise_token_auth

Reply to msms

用代码试一下是最快的,你把 before_action 从 ApplicationController 移到你实际想要控制的 Controller 看看就知道了。

这个放到具体业务 Controller 肯定可以的,就是想确认下放在 ApplicationController 行不行

应该是去掉 before_action :authenticate_sys_user! 就可以了,用 token 做验证时只需要 include DeviseTokenAuth::Concerns::SetUserByToken

可以在 DeviseTokenAuth::SessionsController里加上

skip_before_action : authenticate_sys_user , only: [:create]

You need to Sign in before reply, if you don't have an account, please Sign up first.