2016-03-07 94 views
3

我在轨道上做了一个红宝石api,我试图使用基于令牌的认证。一切正常,但Rails说,方法authenticate_with_http_token是未定义的。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 

回答

8

尝试,包括在你的ApplicationController或UsersController

include ActionController::HttpAuthentication::Token::ControllerMethods 
1

我想你正试图use the new Rails 5 API-only?

如果是这样你可能继承了你ApplicationController

class ApplicationController < ActionController::Base

,而不是

class ApplicationController < ActionController::API

请大家注意的ActionController :: API是不包括ALL的ActionController的缩小版本模块。其中ones left out实际上是ActionController::HttpAuthentication::Token

包括它在你的ApplicationController(或者,如果你只需要在一个地方一个专门的控制器)应该修复它:

include ActionController::HttpAuthentication::Basic