0
我用的宝石jwt
,devise
建立一个用户登录系统,应该将令牌存储到Ruby On Rails中的数据库中吗?
我生成模型验证检查令牌存在与否。
遵循此代码:
型号/ authentication.rb
class Authentication < ApplicationRecord
def self.generate_access_token(email)
payload = {:email => email}
secret = 'secret'
token = JWT.encode payload, secret, 'HS256'
return token
end
end
控制器/用户/ sessions_controller.rb
def create
user = User.where(email: params[:email]).first
if user&.valid_password?(params[:password])
@token = Authentication.generate_access_token(user.email)
Authentication.create(access_token: @token)
authentications = {token: @token, email: user.email}
render json: authentications, status: :created
else
head(:unauthorized)
end
end
当我做一个POST请求user/sessions
我会得到令牌和用户的电子邮件并将其存储在客户端的本地存储中,并帮助我检查令牌是否有效。
遵循此代码:
def authenticate_token
token = Authentication.find_by_access_token(params[:token])
head :unauthorized unless token
end
在我的问题,有没有办法让令牌不需要存储到数据库?
非常感谢,它的工作 –