繁体   English   中英

JWT使Rails上的ruby令牌过期

[英]JWT expire token on ruby on rails

我正在尝试将到期时间设置为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 key:value。

任何建议

UPDATE

我正在使用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

这是一个简单的测试,显示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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM