[英]Rails: How can I check if the access_token is expired?
I'm writing an api for an android app with rails. 我正在为带有Rails的android应用程序编写一个api。 Since I'm new to both rails and android, I cannot figure the access_token stuff out. 由于我是Rails和android的新手,所以我无法弄清access_token的内容。
I have a Token model, each time the user logs in, a new access_token will be added to the tokens table. 我有一个令牌模型,每次用户登录时,都会将一个新的access_token添加到令牌表中。 My question is if I set the expiration date == 3 days after the token is created, what's the proper way to validate this when the user sends a request with an access_token? 我的问题是,如果我将令牌创建后的有效期限设置为== 3天,那么当用户发送带有access_token的请求时,验证此错误的正确方法是什么? How can I delete those expired tokens? 如何删除那些过期的令牌?
Here is my Token Model: 这是我的令牌模型:
# Table name: tokens
#
# id :integer not null, primary key
# access_token :string(255)
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
class Token < ActiveRecord::Base
attr_accessible :access_token, :user_id
before_validation :generate_access_token
belongs_to :user
validates :access_token, presence: true, uniqueness: true
validates :user_id, presence: true, uniqueness: true
private
def generate_access_token
begin
self.access_token = SecureRandom.hex
end while self.class.exists?(access_token: access_token)
end
end
You can add an expires_at
column to the Token model to handle that. 您可以将expires_at
列添加到令牌模型中以进行处理。 You will also need a method of retrieving a new token which could either update the existing token's key and expiration or you can generate a new Token record for the user and return that instead. 您还将需要一种检索新令牌的方法,该方法可以更新现有令牌的密钥和到期时间,也可以为用户生成新的令牌记录并返回该记录。 The latter is more of the approach that Facebook takes for it's access tokens. 后者更多是Facebook为其访问令牌所采用的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.