JWT expire token on ruby on rails
<p>I'm trying to set the expiration time to a jwt token like this:</p>

<pre><code>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
</code></pre>

<p>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.</p>

<p>Any suggestion</p>

<h2>UPDATE</h2>

<p>I'm using the <a href="https://github.com/jwt/ruby-jwt" rel="nofollow" title="jwt">jwt gem</a></p>

<p>This is how I authenticated the user.</p>

<pre><code>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
</code></pre>

<p>Example using curl:</p>

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

<p>This curl return:</p>

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

<p>Then on my rails console:</p>

<pre><code>JWT.decode("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxfQ.wPPX7T6WJ5K8ucjZF_l8-9mG7IzabcusLeWw1UOhhTM", Rails.application.secrets.secret_key_base)
</code></pre>

<p>and get:</p>

<pre><code>[{"user_id"=&gt;1}, {"typ"=&gt;"JWT", "alg"=&gt;"HS256"}]
</code></pre>

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

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