我使用rails构建Rest API。我想实现令牌的到期。它是如何工作的? 我没有实施设计,因为我真的不需要它。 我只想在创建用户时收到令牌刷新令牌。 所以它并不是真正的oauth,因为没有第三方使用api。
This is my user model.
require 'securerandom'
class User
field :auth_token, type: String
field :name, type: String
field :phone, type: String
field :image, type: String
#Generate URLS for different image sizes...
def as_json(options)
json = super
self.image.styles.each do | format |
json = json.merge({"image_"+format[0].to_s => self.image(format[0])})
end
json
end
private
def set_auth_token
return if auth_token.present?
self.auth_token = generate_auth_token
end
def generate_auth_token
SecureRandom.hex(90)
end
end
使用简单生成的令牌工作的简单身份验证。但我认为使用到期令牌更安全。当然,连接是通过SSL进行的。
class ApplicationController < ActionController::API
include ActionController::HttpAuthentication::Token::ControllerMethods
def current_user
@current_user = User.find(params[:user_id])
end
protected
def authenticate
authenticate_token || authentication_request
end
def authenticate_token
authenticate_or_request_with_http_token do |token, options|
User.where(auth_token: token).first
end
end
def authentication_request(controller, realm)
controller.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}")
controller.__send__ :render, :text => "HTTP Token: Access denied.\n", :status => :unauthorized
end
def request_http_token_authentication(realm = "Application")
self.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}")
render :json => {:error => "HTTP Token: Access denied."}, :status => :unauthorized
end
end
答案 0 :(得分:3)
生成令牌时,请保存您希望过期的时间:
class User
field :auth_token, type: String
field :token_expiry, type: Time
def set_auth_token
return if auth_token.present? && token_expiry > Time.now
self.auth_token = generate_auth_token
self.token_expiry = Time.now + 1.day
end
然后当您检查令牌时,也要检查到期日期:
def authenticate_token
authenticate_or_request_with_http_token do |token, options|
user = User.where(auth_token: token).first
user if user.token_expiry > Time.now
end
end