首页 > 解决方案 > 未初始化的常量 AuthenticationController

问题描述

我正在尝试使用 JWT 身份验证对用户进行身份验证,但遇到了问题。

{
  "id": 1,
  "name": "gabriel",
  "username": "gabriel_carneiro",
  "email": "gabriel.bsb98@gmail.com",
  "password_digest": "$2a$12$7K.Z/ixpVM.lOkINboFW5.tvVlPYFnbMTEreVrrR4IClAL.70IQkO",
  "created_at": "2020-06-17T11:13:27.116Z",
  "updated_at": "2020-06-17T11:13:27.116Z"
}

然后我需要对其进行身份验证。我正在使用 Postman 发送它:

邮箱:gabriel.bsb98@gmail.com 密码:12345678

我收到此错误消息:

 {   "status": 500,   "error": "Internal Server Error",   "exception":
 "#<NameError: uninitialized constant
 AuthenticationController::JsonWebToken>",   "traces": {
     "Application Trace": [
       {
         "exception_object_id": 70261772705960,
         "id": 0,
         "trace": "app/controllers/authentication_controller.rb:8:in `login'"
       }

它指责 Authentication Controller 的第 8 行出现错误。这是我的身份验证控制器:

class AuthenticationController < ApplicationController
    before_action :authorize_request, except: :login

    # POST /auth/login
    def login
      @user = User.find_by_email(params[:email])
      if @user&.authenticate(params[:password])
        token = JsonWebToken.encode(user_id: @user.id)
        time = Time.now + 24.hours.to_i
        render json: { token: token, exp: time.strftime("%m-%d-%Y %H:%M"),
                       username: @user.username }, status: :ok
      else
        render json: { error: 'unauthorized' }, status: :unauthorized
      end
    end

    private

    def login_params
      params.permit(:email, :password)
    end

end

我该如何解决这个问题?\ Ps:这是我阅读的教程https://medium.com/binar-academy/rails-api-jwt-authentication-a04503ea3248

标签: ruby-on-railsrubyauthenticationjwt

解决方案


您很可能必须将此行添加到config/application.rb

class Application < Rails::Application
  config.autoload_paths << “#{Rails.root}/lib” 
end

推荐阅读