JWT在rails上的ruby上过期令牌

时间:2016-07-16 16:31:09

标签: ruby-on-rails ruby token jwt

我试图将到期时间设置为这样的jwt令牌:

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

但是当我尝试访问url时,令牌始终有效。此外,如果我解码令牌,我永远不会得到exp键:哈希值。

任何建议

更新

我正在使用jwt gem

这是我对用户进行身份验证的方式。

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

使用curl的示例:

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

这个卷曲回归:

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

然后在我的rails控制台上:

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

并获得:

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

正如您所见,令牌始终有效,即使我在此行设置了到期日期:

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

1 个答案:

答案 0 :(得分:1)

这是一个简单的测试,显示JWT gem工作正常:

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