首页 > 解决方案 > simple_token_authentication - 未定义的方法`authenticate_user

问题描述

我正在使用devisesimple_token_authentication创建一个支持令牌身份验证的 API

我已按照指南中的所有步骤进行操作:

# app/models/user.rb

class User < ApplicationRecord

    acts_as_token_authenticatable

    # Include default devise modules. Others available are:
    # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
    devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable

end
# app/controllers/application_controller.rb
class ApplicationController < ActionController::API
    acts_as_token_authentication_handler_for User
end

当我尝试到达路线“/books”以列出我的模型书的所有条目时,我收到以下错误:

<NoMethodError:
    undefined method `authenticate_user!' for 
    # <BooksController:0x0000563e7bb26820>
    Did you mean?  authenticate_user_from_token!
>

我做错了什么?

更新

更多信息:

$ rails routes
  Prefix Verb   URI Pattern                                            Controller#Action
   books GET    /books(.:format)                                       books#index
         POST   /books(.:format)                                       books#create
    book GET    /books/:id(.:format)                                   books#show
         PATCH  /books/:id(.:format)                                   books#update
         PUT    /books/:id(.:format)                                   books#update
         DELETE /books/:id(.:format)                                   books#destroy
sessions POST   /sessions(.:format)                                    sessions#create
         GET    /books/nearby/:latitude/:longitude/:distance(.:format) books#nearby

更新2

如果有帮助,我已将整个回购公开。查看分支simple_token_auth https://bitbucket.org/enmotent/bookaneer-api/src/master/

标签: ruby-on-railsjwt

解决方案


尝试

class ApplicationController < ActionController::API
    acts_as_token_authentication_handler_for User, fallback: :none
end

class BooksController < ApplicationController
 before_action :requires_login
end


 private
 def requires_login
   unless current_user
     render json: { errors: "This requires login" }
   end
 end
end

推荐阅读