解码的jwt令牌无法从Rails API控制器方法访问



我有一个使用JWT登录的Rails API。Login使用生成并存储在本地存储中的令牌。但是,在解码令牌的基础上授权控制器操作时会遇到问题。

authorize_request在各种控制器中用作before动作。

下面是在application_controller中定义的authorize_request动作:

类ApplicationController

def not_found
render json: { error: 'not_found' }
end
def authorize_request
header = request.headers['Authorization']
header = header.split(' ').last if header
puts "header is #{header}"
begin
@decoded = JsonWebToken.decode(header)
puts "decoded header is #{@decoded}"
@current_user = User.find(@decoded[:user_id])
puts "current_user is #{@current_user}"
rescue ActiveRecord::RecordNotFound => e
render json: { errors: e.message }, status: :unauthorized
rescue JWT::DecodeError => e
render json: { errors: e.message }, status: :unauthorized
end
end
end

下面是JsonWebToken类解码方法:

class JsonWebToken
SECRET_KEY = Rails.application.secrets.secret_key_base
def self.encode(payload, exp = 24.hours.from_now)
payload[:exp] = exp.to_i
JWT.encode(payload, SECRET_KEY)
end
def self.decode(token)
puts("decoding token: #{token}")
decoded = JWT.decode(token, SECRET_KEY)
puts("decoded is #{decoded}")
HashWithIndifferentAccess.new decoded
end
end
根据所包含的put stmts,我可以看到令牌在JWT类中被解码,但在控制器中仍然无法访问:

header is eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNjZiZmQyMDAtZDExMy00NjdlLTkwMmEtMDRjMmI5YjE2ZmUwIiwiZXhwIjoxNjgwNzAyMzExfQ.x95ikz4QeWAdgm2rak_L6eUOqhILsRIepvALGieAwx8
decoding token: eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNjZiZmQyMDAtZDExMy00NjdlLTkwMmEtMDRjMmI5YjE2ZmUwIiwiZXhwIjoxNjgwNzAyMzExfQ.x95ikz4QeWAdgm2rak_L6eUOqhILsRIepvALGieAwx8
decoded is [{"user_id"=>"66bfd200-d113-467e-902a-04c2b9b16fe0", "exp"=>1680702311}, {"alg"=>"HS256"}]
decoded header is {}

JWT.decode(token, SECRET_KEY)返回的是一个数组,而不是一个散列。

将数组传递给HashWithIndifferentAccess.new将返回一个空散列,这就是您返回给控制器的内容

查找包含user_id的数组元素并将其返回给控制器。