【问题标题】:Generate expiring activator token or a key hash in rails manually在 Rails 中手动生成过期的激活器令牌或密钥哈希
【发布时间】:2017-09-28 19:36:53
【问题描述】:

我正在尝试验证一个将在一周后过期的链接。我有一个 activator_token 存储在数据库中,它将用于生成这种格式的链接:http://www.example.com/activator_token。 (而不是由 Devise 或 Authlogic 生成的激活令牌。)

有没有办法让这个激活令牌过期(一周左右)而不与 updated_at 或其他日期进行比较。类似于编码令牌的东西,一周后解码时将返回 nil。 Ruby 中的任何现有模块都可以做到这一点吗?我不想将生成的日期存储在数据库或 Redis 等外部存储中,并将其与 Time.now 进行比较。我希望它非常简单,并且想知道这样的东西是否已经存在,然后再编写逻辑。

【问题讨论】:

  • 为什么不想把生成的日期存入数据库呢?我要做的是使用github.com/javan/whenever 运行定期 rake 任务,通过检查对象上的日期来从数据库中删除过期的东西。我会随时使用,因为它与 capistrano 配合得很好
  • 不是不想存。想知道是否有任何现有的机制可以处理到期,比如如果我在到期后尝试解码编码的令牌,它将返回 nil。如果没有类似的东西,我将不得不像你说的那样写一些逻辑。
  • 现在我明白了!长话短说,你想使用github.com/jwt/ruby-jwt
  • 太棒了!这就是我要找的!您可以将其添加为答案,达米亚诺! :)
  • @DamianoStoffie ,有没有办法减少这个 JSON Web 令牌的长度?我需要在 URL 中使用它。

标签: ruby ruby-on-rails-4 token


【解决方案1】:

您要使用的是:https://github.com/jwt/ruby-jwt。 这是一些样板代码,您可以自己尝试一下。

require 'jwt'

# generate your keys when deploying your app.
# Doing so using a rake task might be a good idea
# How to persist and load the keys is up to you!
rsa_private = OpenSSL::PKey::RSA.generate 2048
rsa_public = rsa_private.public_key

# do this when you are about to send the email
exp = Time.now.to_i + 4 * 3600
payload = {exp: exp, discount: '9.99', email: 'user@example.com'}
# when generating an invite email, this is the token you want to incorporate in
# your link as a parameter
token = JWT.encode payload, rsa_private, 'RS256'
puts token
puts token.length

# this goes into your controller
begin
    #token = params[:token]
    decoded_token = JWT.decode token, rsa_public, true, { :algorithm => 'RS256' }
    puts decoded_token.first
    # continue with your business logic
rescue JWT::ExpiredSignature
    # Handle expired token
    # inform the user his invite link has expired!
    puts "Token expired"
end

【讨论】:

    猜你喜欢
    • 2015-06-28
    • 2013-06-22
    • 2012-08-12
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    相关资源
    最近更新 更多