【问题标题】:devise auth token current_user return nil设计身份验证令牌 current_user 返回 nil
【发布时间】:2018-10-25 20:13:30
【问题描述】:

我想在devise aoth token gem 中访问current_user,但它返回nil 或错误:"You need to sign in or sign up before continuing."

我在客户端使用redux-token-auth包,客户端登录并注册用户成功

但在服务器端 Rails-api 我无法获取 current_user 数据

Rails 服务器在端口:3001 端口中的客户端服务器:3000

宝石:

gem 'devise-i18n'
gem 'devise_token_auth'
gem 'omniauth'
gem 'devise'

应用控制器:

class ApplicationController < ActionController::Base
   include DeviseTokenAuth::Concerns::SetUserByToken
   protect_from_forgery with: :null_session
end

设计身份验证令牌

DeviseTokenAuth.setup do |config|
  config.change_headers_on_each_request = false
  config.token_lifespan = 10.day
end

路线:

Rails.application.routes.draw do
  mount_devise_token_auth_for 'User', at: 'auth'
  namespace :api, defaults: { format: :json } do 
    namespace :v1 do 
     resources :wallets , only: [:index, :show]
    end 
  end 
end 

机架 CROS:

config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*', headers: :any, methods: [:get, :post, :options, :delete, :put]
      end
    end 

【问题讨论】:

    标签: ruby-on-rails devise react-redux rails-api devise-token-auth


    【解决方案1】:

    根据documentation,可以在认证方法中包含命名空间:

    before_action :authenticate_api_v1_user!
    

    那么当前用户将是:

    current_api_v1_user
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-18
      • 2018-04-23
      • 1970-01-01
      • 2016-02-15
      • 1970-01-01
      • 2017-01-01
      • 2016-05-08
      相关资源
      最近更新 更多