Bil*_*fas 0 ruby api rest ruby-on-rails backend
我用 Rails 构建了一个 Rest API。我想实现令牌的到期。它是如何工作的?我不实施设计,因为我真的不需要。我只希望在创建用户时他收到一个令牌刷新令牌。所以它并不是真正的 oauth,因为没有 3rd 方使用 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
Run Code Online (Sandbox Code Playgroud)
使用简单生成的令牌进行如此简单的身份验证。但我认为使用过期令牌更安全。当然,连接是通过 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
Run Code Online (Sandbox Code Playgroud)
生成令牌时,请保存您希望它到期的时间:
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
Run Code Online (Sandbox Code Playgroud)
然后,当您检查令牌时,也要检查到期时间:
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
Run Code Online (Sandbox Code Playgroud)