Rails 5 API 出现错误 OmniAuth::NoSessionError

Getting error OmniAuth::NoSessionError with Rails 5 API

我用 rails new appname --api 创建了一个新的 Rails 5 应用程序,看起来很棒!我想将它用作 React 前端的后端,并及时使用 Chrome 应用程序。现在我想创建一个 API.

我用了下面的gems

我按照他们 Github 上的说明进行了设置:http://www.developingandrails.com/2015/02/api-authentication-with-devisetokenauth.html

现在当我 运行 我得到的应用程序时:

Started GET "/" for 14.144.15.10 at 2016-07-17 17:21:46 +0000
  ActiveRecord::SchemaMigration Load (0.1ms)  SELECT "schema_migrations".* FROM "schema_migrations"
OmniAuth::NoSessionError (You must provide a session to use OmniAuth.):

我在 Github 和 Whosebug 上寻找答案,但似乎没有人有解决方案。

唯一似乎 "fix" 问题是添加这个:

 # config/application.rb
 config.middleware.use Rack::Session::Cookie

但是这个 "solution" 在控制台中给我这个错误:

SECURITY WARNING: No secret option provided to Rack::Session::Cookie.
        This poses a security threat. It is strongly recommended that you
        provide a secret to prevent exploits that may be possible from crafted
        cookies. This will not be supported in future versions of Rack, and
        future versions will even invalidate your existing user cookies.

请帮忙!谢谢。

不太确定,但在项目中对我有用的是:

  #config/application.rb
  config.middleware.insert_after(ActiveRecord::QueryCache, ActionDispatch::Cookies)
  config.middleware.insert_after(ActionDispatch::Cookies, ActionDispatch::Session::CookieStore)

不幸的是,omniauth 需要 rack.session 存在才能在提供者请求和回调请求之间保留一些数据。

https://github.com/omniauth/omniauth/blob/master/lib/omniauth/strategy.rb#L173

要使用 Rails 的 Omniauth API 需要 return 到中间件堆栈的会话:

config.middleware.insert_after ActiveRecord::Migration::CheckPending, ActionDispatch::Cookies
config.middleware.insert_after ActionDispatch::Cookies, ActionDispatch::Session::CookieStore

虽然 config.middleware.insert_after 对我有用,但没有加载相同的中间件,因此我不得不插入选择其他东西以在之后插入它。我在 中找到了类似的答案并简单地添加了:

config.middleware.use ActionDispatch::Cookies
config.middleware.use ActionDispatch::Session::CookieStore

application.rb.

在您的 config/application.rb 中设置 secret

config.middleware.use Rack::Session::Cookie, secret: "s3cr3t_k3y_3x@mpl3"

参考:https://www.rubydoc.info/gems/rack/Rack/Session/Cookie