我正在使用ruby on rails制作api,我正在尝试使用基于令牌的身份验证。一切正常,但Rails说方法authenticate_with_http_token
未定义。
这是它给出的错误:
{"status":500,"error":"Internal Server Error","exception":"#\u003cNoMethodError: undefined method `authenticate_with_http_token' for #\u003cUsersController:0x007fa8ac16dee0\u003e\u003e","traces":{"Application Trace":[{"id":0,"trace":"app/controllers/users_controller.rb:59:in `authenticate_token'"},{"id":1,"trace":"app/controllers/users_controller.rb:55:in `authenticate'"}],"Framework Trace":[{"id":2,"trace":"activesupport (5.0.0.beta3) lib/active_support/callbacks.rb:382:in `block in make_lambda'"}
这是我的控制器的代码:
class UsersController < ApplicationController
before_action :set_user, only: [:show, :update, :destroy]
before_action :authenticate, only: [:show, :update, :destroy]
# GET /users
def index
@users = User.all
render json: @users
end
# GET /users/1
def show
render json: @user
end
# POST /users
def create
@user = User.new(user_params)
if @user.save
render json: @user, status: :created, location: @user
else
render json: @user.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /users/1
def update
if @user.update(user_params)
render json: @user
else
render json: @user.errors, status: :unprocessable_entity
end
end
# DELETE /users/1
def destroy
@user.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def user_params
params.require(:user).permit(:first_name, :last_name, :email, :school_id, :auth_token, :password_digest)
end
def authenticate
authenticate_token || render_unauthorized
end
def authenticate_token
authenticate_with_http_token { |token, options| User.find_by(auth_token: token) }
end
end
答案 0 :(得分:8)
尝试将其包含在ApplicationController或UsersController
中include ActionController::HttpAuthentication::Token::ControllerMethods
答案 1 :(得分:2)
我猜您正在尝试use the new Rails 5 API-only?
如果是这样,您可能从
继承了ApplicationController
class ApplicationController < ActionController::API
而不是
class ApplicationController < ActionController::Base
请注意,ActionController :: API是ActionController的缩小版,不包含ALL个模块。其中一个ones left out实际上是ActionController::HttpAuthentication::Token
。
将它包含在您的ApplicationController中(如果您只需要在一个地方使用专用控制器)应该修复它:
include ActionController::HttpAuthentication::Basic