Search code examples
error-handlingjwtverificationexception

jwt error with method `verify_expiration'


I had a question when I try to use JWT to decode the token that is sent back from the frontend. When the token is decoded to be “2”, which is a user id for me to grab the user in the backend, I got this error: “NoMethodError: undefined method `include?’ for 2:Integer”, which is from the following codes in JWT source codes:

def verify_expiration
return unless @payload.include?('exp')
raise(JWT::ExpiredSignature, 'Signature has expired') if @payload['exp'].to_i <= (Time.now.to_i - exp_leeway)
end

What should I do to fix this?

my application controller file looks like this:

class ApplicationController < ActionController::API

    def encode_token(payload)
        JWT.encode(payload, 'secret')
    end

    def auth_header_token
        request.headers['Authorization'].split(' ')[1]
    end

    def session_user
      binding.pry
      decoded_hash = decoded_token
      if !decoded_hash.empty?
        user_id = decoded_hash[0]["user_id"]
        user = User.find_by :id=>user_id
      end
    end


    def decoded_token
        if auth_header_token
          begin
            JWT.decode(auth_header_token, 'secret',true, algorithm: 'HS256')
          rescue JWT::DecodeError
            []
          end
        end
    end
end

my session_controller looks like this:

class SessionController < ApplicationController
    def login
        user = User.find_by :email=>params[:email]
        if user && user.authenticate(params[:password])
            payload = user.id
            token = encode_token(payload)
            render json: {
                user:user, include: ['order', 'favorites','orders.dishes','favorites.dishes'], 
                jwt:token
            }
        else
            render json: {status: "error", message: "We don't find such an user according to your information,please try again."}
        end
    end


    def auto_login
        if session_user
            render json: session_user
        else
            render json: {errors: "No User Logged In."}
        end     
    end
end

Should I change the way I encode user_id?


Solution

  • Just found that the problem is I need to encode user_id as an object, not just the id itself, because JWT can check it as an object, and that is where the error message comes from. So, instead of

    payload = user.id
    token = encode_token(payload)
    

    should have set:

    payload = {user_id: user.id}
    token = encode_token(payload)