【问题标题】:Rails : API : Devise : current_user nilRails:API:设计:current_user nil
【发布时间】:2015-02-03 20:35:43
【问题描述】:

我正在开发 Rails API 并使用 Devise 进行身份验证。

当我在控制器中使用current_user 时,它总是返回nil(好像没有登录用户一样),尽管用户已经登录。

为什么它在开发网站时有效而在开发 API 时无效?

我正在使用 curl 命令来测试应用程序:

登录:

curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST http://localhost:3000/api/v1/sessions -d "{\"user\":{\"email\":\"user1@example.com\",\"password\":\"secret123\"}}"   

退出:

curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X DELETE http://localhost:3000/api/v1/sessions/\?auth_token\=JRYodzXgrLsk157ioYHf

【问题讨论】:

标签: ruby-on-rails api authentication devise


【解决方案1】:

您是否在为任何控制器命名空间?

即:

我有:

命名空间:api,默认值:{格式::json}做

devise_for :users, controllers: {

  registrations: 'api/registrations',
  sessions:      'api/sessions'
}

结束

在我的 routes.rb 中

我想使用#current_user 和#user_signed_in? Devise 应该提供的方法,但不断收到“nil”和 undefined_method 错误

阅读了一些关于命名空间的内容,并意识到设计有很多神奇的力量。由于我在 api 中为我的用户命名,因此设计生成:current_api_user & api_user_signed_in?适合我的方法。这些没有返回 nil

您可以在此处阅读更多信息: https://github.com/plataformatec/devise/blob/master/lib/devise/rails/routes.rb#L61

【讨论】:

    猜你喜欢
    • 2015-04-01
    • 1970-01-01
    • 2011-10-27
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多