我用rails new appname --api
创建了一个新的Rails 5应用程序,看起来很棒!我希望将它用作React前端的后端,并及时使用Chrome应用程序。现在我想创建一个API。
我使用了以下宝石
我按照他们的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和StackOverflow上寻找答案,但似乎没有人有解决方案。
唯一似乎“解决”问题的是添加这个:
# config/application.rb
config.middleware.use Rack::Session::Cookie
但是这个“解决方案”在控制台中给了我这个错误:
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)
虽然config.middleware.insert_after
为我工作,但相同的中间件没有加载,所以我不得不插入选择其他东西插入后。我在http://stackoverflow.com/questions/15342710/adding-cookie-session-store-back-to-rails-api-app找到了类似的答案,并简单地补充说:
config.middleware.use ActionDispatch::Cookies
config.middleware.use ActionDispatch::Session::CookieStore
在application.rb
。
不幸的是,omniauth要求rack.session
存在以在请求提供者和回调请求之间保留一些数据。
https://github.com/omniauth/omniauth/blob/master/lib/omniauth/strategy.rb#L173
对于带有Rails API的Omniauth,需要将会话返回到中间件堆栈:
config.middleware.insert_after ActiveRecord::Migration::CheckPending, ActionDispatch::Cookies
config.middleware.insert_after ActionDispatch::Cookies, ActionDispatch::Session::CookieStore
在你的config/application.rb
设置secret
config.middleware.use Rack::Session::Cookie, secret: "s3cr3t_k3y_3x@mpl3"