在Rails中,可以使用Devise或JWT(JSON Web Token)来实现会话过期时间的控制。以下是使用Devise和JWT的解决方法的代码示例:
使用Devise:
gem 'devise'
bundle install
安装gemrails generate devise:install
来生成配置文件config/initializers/devise.rb
文件中找到config.timeout_in
配置项,并将其设置为1小时:config.timeout_in = 1.hour
before_action :authenticate_user!
,以确保用户已登录skip_before_action :verify_authenticity_token
,以防止会话过期时的CSRF错误使用JWT:
gem 'jwt'
bundle install
安装gemsessions_controller.rb
文件,并添加以下代码:class SessionsController < ApplicationController
def create
user = User.find_by(email: params[:email])
if user&.authenticate(params[:password])
payload = { user_id: user.id, exp: Time.now.to_i + 1.hour }
token = JWT.encode(payload, Rails.application.secrets.secret_key_base)
render json: { token: token }
else
render json: { error: 'Invalid email or password' }, status: :unauthorized
end
end
end
before_action :authenticate_user
,以确保用户已登录,可以使用以下代码示例:class SomeController < ApplicationController
before_action :authenticate_user
def index
# ...
end
end
authenticate_user
方法,在该方法中验证JWT并设置当前用户,可以使用以下代码示例:class ApplicationController < ActionController::API
def authenticate_user
token = request.headers['Authorization']&.split(' ')&.last
decoded_token = JWT.decode(token, Rails.application.secrets.secret_key_base).first
user_id = decoded_token['user_id']
@current_user = User.find(user_id)
rescue JWT::DecodeError, ActiveRecord::RecordNotFound
render json: { error: 'Unauthorized' }, status: :unauthorized
end
end
请注意,以上代码示例仅为演示目的,可能需要根据你的具体需求进行调整和改进。
上一篇:AngularJS / Promises / DataTables - 没有数据在表格中
下一篇:AngularJS / Sqlite / Electron - 未知提供者:$dbServiceProvider