2016-03-07 2 views
3

Я делаю api с ruby ​​на рельсах, и я пытаюсь использовать аутентификацию на основе токенов. Все работает нормально, но 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 является сокращенной версией ActionController, которая не включает в себя ALL модули. Одним из ones left out является фактически ActionController::HttpAuthentication::Token.

Включая его в ApplicationController (или специализированный контроллер, если вам просто нужно в одном месте) следует исправить:

include ActionController::HttpAuthentication::Basic

Смежные вопросы