我只使用 Rails 7 API 和 gem
devise-jwt
进行身份验证。首先,这是设置教程:https://dakotaleemartinez.com/tutorials/devise-jwt-api-only-mode-for-authentication/
有一个问题,当我调用 API 注册新帐户时,它显示错误:
Your application has sessions disabled. To write to the session you must first configure a session store
我尝试解决这个问题(将会话存储配置添加到应用程序配置中)
config.session_store :cookie_store, key: '_rails7_api_session'
config.middleware.use ActionDispatch::Cookies
config.middleware.use config.session_store, config.session_options
=> 它起作用了,但我遇到了第二个麻烦。我定义了一个“/me”路由来获取当前用户。理论上,我需要在标头上传递
Authorization
参数才能获取当前用户数据(我使用的是Postman)。但不知何故(可能是因为会话)我得到的用户数据没有标题上的Authorization
参数。
我想解决这个问题。有人可以帮助我吗?
在相关的
/me
控制器中,你有没有放
before_action :authenticate_user!
在控制器中?
但是,您可以尝试解决会话存储错误的已发布方法。
首先去掉session store相关的配置,因为它对于一个API only APP来说是不必要的。
然后尝试:
我找到了一种集中配置存储的方法:false,而不是分别覆盖可能需要它的每个方法:
#config/initializers/devise.rb
Devise.setup do |config|
# ... other config
config.warden do |warden|
warden.scope_defaults :user, store: false # <---- This will use the config even if it's not passed to the method opts
warden.scope_defaults :admin, store: false # <---- You need to configure it for each scope you need it for
# you might also want to overwrite the FailureApp in this section
end
end
# config/application.rb
module YourApp
class Application < Rails::Application
# ... other config
config.session_store :disabled
end
end
我知道 Devise 严重依赖依赖会话的 warden 等,或者至少是它的假版本。因此,我们通过创建这个关注点/模块来规避这个问题,我们已经将其包含在我们应用程序中与 Devise 相关的控制器中:
module RackSessionFixController
extend ActiveSupport::Concern
class FakeRackSession < Hash
def enabled?
false
end
end
included do
before_action :set_fake_rack_session_for_devise
private
def set_fake_rack_session_for_devise
request.env['rack.session'] ||= FakeRackSession.new
end
end
end