【问题标题】:How to get JWT token in header when using Rails and React使用 Rails 和 React 时如何在标头中获取 JWT 令牌
【发布时间】:2020-05-27 21:52:54
【问题描述】:

我的 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-rails reactjs authentication jwt token


    【解决方案1】:

    想通了。

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

    【讨论】:

      猜你喜欢
      • 2015-07-03
      • 2020-06-09
      • 1970-01-01
      • 2021-04-20
      • 2020-11-16
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 2014-09-02
      相关资源
      最近更新 更多