gpt4 book ai didi

ruby-on-rails - JWT 在 ruby​​ on rails 上过期 token

转载 作者:行者123 更新时间:2023-12-04 12:51:05 26 4
gpt4 key购买 nike

我正在尝试将过期时间设置为这样的 jwt token :

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 时, token 始终有效。此外,如果我解码 token ,我永远不会在哈希上获得 exp key:value。

任何建议

更新

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

此 curl 返回:
{"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"}]

如您所见,即使我在这一行设置了过期时间, token 也始终有效:
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

关于ruby-on-rails - JWT 在 ruby​​ on rails 上过期 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38413215/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com