Jean Jean - 4 months ago 37
Ruby Question

JWT expire token on ruby on rails

I'm trying to set the expiration time to a jwt token like this:

class JsonWebToken
def self.encode(payload)
payload[:exp] = (2).minutes.from_now.to_i #expire in 2 minutes
JWT.encode(payload, Rails.application.secrets.secret_key_base)
end

def self.decode(token)
return HashWithIndifferentAccess.new(JWT.decode(token, Rails.application.secrets.secret_key_base)[0])
rescue
nil
end
end


But when I try to access the url the token is always valid. Also if I decode the token I never get the exp key:value on the hash.

Any suggestion

UPDATE



I'm using the jwt gem

This is how I authenticated the user.

def authenticate_user
user = User.find_for_database_authentication(email: params[:email])
if user.valid_password?(params[:password])
render json: payload(user)
else
render json: {errors: ['Invalid Username/Password']}, status: :unauthorized
end
end

private

def payload(user)
return nil unless user and user.id
{
auth_token: JsonWebToken.encode({user_id: user.id}),
user: {id: user.id, email: user.email}
}
end


Example using curl:

curl -X POST -d email="a@a.com" -d password="changeme" http://localhost:3000/auth_user


This curl return:

{"auth_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxfQ.wPPX7T6WJ5K8ucjZF_l8-9mG7IzabcusLeWw1UOhhTM","user":{"id":1,"email":"a@a.com"}}


Then on my rails console:

JWT.decode("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxfQ.wPPX7T6WJ5K8ucjZF_l8-9mG7IzabcusLeWw1UOhhTM", Rails.application.secrets.secret_key_base)


and get:

[{"user_id"=>1}, {"typ"=>"JWT", "alg"=>"HS256"}]


as you can see the token is always valid, even though I set the expiration on this line:

def self.encode(payload)
payload[:exp] = (2).minutes.from_now.to_i #expire in 2 minutes <<--- This one
JWT.encode(payload, Rails.application.secrets.secret_key_base)
end

Answer

Here's a simple test that shows the JWT gem is working properly:

require 'JWT'

class JsonWebToken
  def self.encode(payload, expiration)
    payload[:exp] = expiration
    JWT.encode(payload, 'SECRET')
  end

  def self.decode(token)
    return JWT.decode(token, 'SECRET')[0]
  rescue
    'FAILED'
  end
end

# expire 2 minutes from now
token = JsonWebToken.encode({ :hello => 'world' }, Time.now.to_i + 120)
puts token # eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJoZWxsbyI6IndvcmxkIiwiZXhwIjoxNDY4Njg3OTc1fQ.NhIsdEa0Q7Wl5Dx6kyJvSZY6E8ViJ5Kooo7rKr2OBPg
puts JsonWebToken.decode(token) # {"hello"=>"world", "exp"=>1468687975}

# expire 2 minutes ago
token = JsonWebToken.encode({ :hello => 'world' }, Time.now.to_i - 120)
puts token # eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJoZWxsbyI6IndvcmxkIiwiZXhwIjoxNDY4Njg3NzM1fQ.kDD_WWN3ZTTdFXQvYEgm1CgDaE1mEZxjMvQkQEq4HX8
puts JsonWebToken.decode(token) # FAILED
Comments