ruby-on-rails - 使用 Rails 和 React 时如何在标头中获取 JWT 令牌
问题描述
我的 Sessions 控制器设置如下。我正在寻找一种方法来从身份验证方法中的 command.result 中获取 auth_token,并在用户登录时使其在我的标头中可用,以便我可以在内部访问它以响应每个请求对用户进行身份验证。
当我向身份验证操作发出请求时,我得到了带有 auth_token 的正确响应,但不知道如何将此响应发送到标头并在那里使用它。
class Api::V1::SessionsController < ApplicationController
skip_before_action :authenticate_request
include CurrentUserConcern
def authenticate
command = AuthenticateUser.call(params[:email], params[:password])
if command.success?
render json: { auth_token: command.result, message: 'Login successful' }
else
render json: { error: command.errors }, status: :unauthorized
end
end
def create
user = User.find_by(email: params[:email])
.try(:authenticate, params[:password])
if user
session[:user_id] = user.id
render json: {
status: :created,
logged_in: true,
user: user,
}
else
render json: {
status: 400,
}, status: 400
end
end
def logged_in
if @current_user
render json: {
logged_in: true,
user: @current_user
}
else
render json: {
logged_in: false
}
end
end
def logout
reset_session
render json: { status: 200, logged_out: true }
end
end
解决方案
弄清楚了。
我在控制器中设置了一个 before_action 来设置 @token 变量。这样我就可以在控制器内的任何操作中使用@token。
class Api::V1::SessionsController < ApplicationController
skip_before_action :authenticate_request
before_action :set_token
end
然后我创建了一个私有方法来设置令牌。
def set_token
command = AuthenticateUser.call(params[:email], params[:password])
if command.success?
@token = command.result
else
nil
end
end
并在我的创建操作中调用@token 变量,将其传递给 set_headers。
response.set_header('token', @token)
推荐阅读
- reactjs - 两个组件之间的访问功能反应js
- php - 根据环境变量运行 Laravel 命令
- javascript - SAPUI5如何在浏览器中压缩所有下载的文件
- flutter - petitparser 未解析 ref0
- jquery - 使用 dhtmlx 5.0 和 wijmo 网格在 Web 应用程序中拖放列表项时出现问题
- tensorboard - Tensorboard 显示带有 S3 URL 的空仪表板
- python - 如何更改我的 Heroku 管理命令以使用工作人员测功机
- c# - 向上转换子实体到父级不起作用c#
- ios - 在 macos/ios 中从工作线程创建 UI
- reactjs - Webpack 尝试解析已删除的 CSS 文件(模块)