首页 > 解决方案 > 使用 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

标签: ruby-on-railsreactjsauthenticationjwttoken

解决方案


弄清楚了。

我在控制器中设置了一个 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)

推荐阅读