Rails中JWT认证遇Nil JSON Web Token错误求助
问题分析与修复方案
核心问题定位
你调用创建用户接口时触发了UsersController#index的JWT错误,大概率是请求方法错误:使用了GET /users(会触发需要认证的index方法)而非POST /users(对应无需认证的create方法)。另外代码里还存在几处语法与逻辑问题,一并修复:
步骤1:确认请求方式与路由
确保调用创建用户接口时使用POST请求,路径为http://localhost:3000/users。如果你的路由配置是默认的RESTful路由(resources :users),POST /users会正确映射到UsersController#create方法,该方法已通过skip_before_action :authenticate_request, only: [:create]跳过了JWT认证。
步骤2:修复AuthenticationController的语法错误
login方法里缺少赋值运算符,导致无法正确获取用户并生成token:
# 错误代码 @user User.find_by_email (params[:email]) # 修复后 @user = User.find_by_email(params[:email])
步骤3:完善JWT认证的异常处理
在authenticate_request方法中添加token为空的判断,避免直接传入nil到jwt_decode导致报错:
private def authenticate_request header = request.headers["Authorization"] header = header.split(" ").last if header # 新增token为空的处理 unless header render json: { error: "Missing authentication token" }, status: :unauthorized return end decoded = jwt_decode(header) @current_user = User.find(decoded[:user_id]) rescue JWT::DecodeError render json: { error: "Invalid authentication token" }, status: :unauthorized rescue ActiveRecord::RecordNotFound render json: { error: "User not found" }, status: :not_found end
同时修改jwt_decode方法,确保鲁棒性:
def jwt_decode(token) return {} unless token.present? decoded = JWT.decode(token, SECRET_KEY)[0] HashWithIndifferentAccess.new(decoded) end
步骤4:清理ApplicationController的重复配置
移除重复的protect_from_forgery配置,保留适合API的null_session:
class ApplicationController < ActionController::Base require 'stripe' Stripe.api_key = 'sk_test_51O1pqnSCcF3F1d0MklDFQ0DIDSQ366PJh3YVx8AEqZH5OYRDjIMKOQdACJ5dxNiMkAH4dZdAZy48yzp6FKS3KMAy00VB8RVFBI' # 保留这一行即可 protect_from_forgery with: :null_session include JsonWebToken before_action :authenticate_request # ... 其他代码 end
验证修复
- 先调用
POST /auth/login接口,确保能正确返回token(修复语法错误后应该可以正常生成)。 - 使用
POST /users请求创建用户,此时不会触发JWT认证,应该能正常执行create方法。 - 调用
GET /users时需要在请求头带上Authorization: Bearer <你的token>,否则会返回友好的错误提示。
内容的提问来源于stack exchange,提问作者Sid
相关产品推荐
相关产品推荐

