current_user是nil,并且user_signed_in?通过设计返回错误的react-rails

问题描述 投票:0回答:1

我有一个Rails 5.2应用程序,最初是用Devise和普通的erb文件构建的。我可以检查前端的current_user等等。

现在,我正在尝试将其缓慢移至React前端。我没有更改任何设置,但控制器的create操作为user_signed_in?返回false,但在索引处返回true。我没有在请求中传递标题吗?

示例代码

class FanciesController < ApplicationController

  skip_before_action :verify_authenticity_token, only: :search_fancy
  after_action :verify_authorized

  def index
    @fancies = Fancy.all

    authorize @fancies

    respond_to do |format|
      format.html { render :index }
      format.json { render json: {...}, status: :ok }
    end
  end

  def create
    @fancy = Fancy.new(...)
    authorize @fancy

    respond_to do |format|
      if @fancy.save
        format.html { redirect_to @fancy, notice: 'Availability was successfully created.' }
        format.json { render :show, status: :created, json: {..}}
      else
        format.html { render :new }
        format.json { render json: {...}, status: :unprocessable_entity }
      end
    end
  end

end

前端代码:

#index.html.erb

<%= react_component("FancyScreen", { selection_fancies: @fancies }) %>

反应成分:

class FancyScreen extends React.Component {
  ...
    onCreateClick(selected_time) {
      const headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' };

      const requestOptions = {
        method: 'POST',
        headers: headers,
        body: JSON.stringify({...})
      }

      fetch(curl_url, requestOptions)
      .then(response => response.json())
      .then(data => {

        new_fancy.push(data)
        fn.setState({
          fancies: new_fancy
        });
      });
    }
  }
}

我尝试通过标题传递csrf令牌,但仍然无法正常工作。

‘X-CSRF-TOKEN’: $(‘meta[name=”csrf-token”]’).attr(‘content’)

我绝对不在,我错过了一些基本知识,但是如果有人可以指出我正确的方向,我相信我能弄清楚。我尝试安装devise-jwt gem,但看起来并不是我真正想要的。

关于我在做什么错的任何想法?

ruby-on-rails authentication devise pundit react-rails
1个回答
0
投票

IMO为了在React-Rails集成中对用户进行身份验证,您需要使用基于令牌的身份验证系统。检查devise_token_auth宝石。首次登录后,会向您发送client-idtoken-iduid。将它们存储在cookie中,并且每次进行API调用时,都将它们发送到标头中。 API将刷新这些值并将其发送回前面。再次使用新值更新cookie,然后继续执行该过程。

© www.soinside.com 2019 - 2024. All rights reserved.